Javascript 如何在等待redux解析时禁用按钮?
在下面的示例中,如何在地理位置请求期间禁用该按钮?在这个.props.inProgress没有设置在init上的情况下,我想在请求getCurrentPosition时禁用按钮,并在解析RECEIVE_位置时启用。什么是正确的方法?我需要使用状态并将道具复制到GeoButton吗Javascript 如何在等待redux解析时禁用按钮?,javascript,reactjs,redux,redux-thunk,Javascript,Reactjs,Redux,Redux Thunk,在下面的示例中,如何在地理位置请求期间禁用该按钮?在这个.props.inProgress没有设置在init上的情况下,我想在请求getCurrentPosition时禁用按钮,并在解析RECEIVE_位置时启用。什么是正确的方法?我需要使用状态并将道具复制到GeoButton吗 export function getGeolocation() { return dispatch => { if (navigator.geolocation) { navigator
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()
导出函数getGeolocation(){
返回调度=>{
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(函数(位置){
派遣({
键入:“接收位置”,
协调:{
纬度:位置。坐标。纬度,
经度:position.coords.longitude,
进展:错误,
},
});
});
}
}
}
导出函数地理位置(状态={},操作){
开关(动作类型){
案例“接收地点”:
var newState=action.coords;
返回新闻状态;
违约:
返回状态;
}
}
类GeoButton扩展React.Component{
建造师(道具){
超级(道具);
}
查找位置(e){
e、 预防默认值();
this.props.dispatch(getGeolocation());
}
render(){
console.log(this.props);//在init geolocation对象上为空
var self=这个;
返回(
获取位置
)
}
}
导出默认连接(状态=>({
地理位置:state.geolocation
}))(地理按钮);//只给它分派()
在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
}
});
});
}
};
}
你的减速器应该是这样的。我调整了state对象的结构,将应用程序数据与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标志。减速器可以从动作类型派生。您不能使用inProgress标志吗?类似于disabled=“inProgress”的内容是否最好在构造函数中设置与预期数据对应的状态对象,并在解析后用此数据替换此状态?我不确定什么方法是正确的,在这种情况下,当前的解决方案不起作用。