在以下示例中,如何在地理位置请求期间禁用按钮?在this.props.inProgress没有在init上设置,我想在请求getCurrentPosition时禁用按钮,如果解决了RECEIVE_LOCATION则启用。什么是正确的方法?我是否要将状态和复制道具用于GeoButton?
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()
答案 0 :(得分:6)
在redux中执行异步时,通常需要调用dispatch两次。一个同步,一个异步。
你的行动应该是这样的:
export function getGeolocation() {
return dispatch => {
dispatch({ type: 'FETCHING_LOCATION' });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
dispatch({
type: 'RECEIVE_LOCATION',
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
});
});
}
};
}
你的减速机应该是这样的。我已经调整了状态对象的结构,将应用程序数据与ui数据分开。
export function geolocation(state = {}, action) {
switch (action.type) {
case 'RECEIVE_LOCATION':
return {
coords: action.coords,
inProgress: false
};
case 'FETCHING_LOCATION':
return {
coords: null,
inProgress: true
};
}
return state;
}
您的动作创建者无需设置inProgress标志。 reducer可以从动作类型派生出来。