2
在以下示例中,如何在地理位置請求期間禁用按鈕?在this.props.inProgress沒有設置在init上,我想在請求getCurrentPosition時禁用按鈕,如果解決了RECEIVE_LOCATION則啓用。什麼是正確的方法?我是否使用狀態和複製道具到GeoButton?如何在等待redux解決時禁用按鈕?
export function getGeolocation() {
return dispatch => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
dispatch({
type: 'RECEIVE_LOCATION',
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
inProgress: false,
},
});
});
}
}
}
export function geolocation(state={}, action) {
switch (action.type) {
case 'RECEIVE_LOCATION':
var newState = action.coords;
return newState;
default:
return state;
}
}
class GeoButton extends React.Component {
constructor(props) {
super(props);
}
findLocation(e) {
e.preventDefault();
this.props.dispatch(getGeolocation());
}
render() {
console.log(this.props); // on init geolocation object is empty
var self = this;
return (
<div>
<button type="button" onClick={this.findLocation} disabled={self.props.geolocation.inProgress}>Get location</button>
</div>
)
}
}
export default connect(state => ({
geolocation: state.geolocation
}))(GeoButton); // just gives it dispatch()
不能使用inProgress標誌?像disabled =「inProgress」 – Radu
是不是更好的設置對應於預期數據的構造函數狀態對象,並解決時,然後用此數據替換此狀態?我不確定在這種情況下哪種方法是正確的,目前的解決方案不起作用。 – luzny