Javascript 组件中的多个分派将发生反应
我在两个不同的动作中有两种方法Javascript 组件中的多个分派将发生反应,javascript,reactjs,redux,Javascript,Reactjs,Redux,我在两个不同的动作中有两种方法 import { fetchCategories } from "../../../actions/elementsActions" import { fetchPlaces } from "../../../actions/placesActions" 而componentWillMount方法是: componentWillMount() { this.props.dispatch(fetchCategories()) this.props.
import { fetchCategories } from "../../../actions/elementsActions"
import { fetchPlaces } from "../../../actions/placesActions"
而componentWillMount方法是:
componentWillMount() {
this.props.dispatch(fetchCategories())
this.props.dispatch(fetchPlaces())
}
我想确保在获取位置之前获取fetchCategories。这样做对吗
更新
行动:
从“axios”导入axios;
导出函数fetchPlaces(){
返回功能(调度){
axios.get(“/getPlaces”)
。然后((响应)=>{
控制台日志(响应);
分派({type:“FETCH_PLACES_completed”,有效负载:response.data})
})
.catch((错误)=>{
分派({type:“FETCH\u PLACES\u REJECTED”,有效负载:err})
})
}
}
调度是同步的,但这只能保证在fetchPlaces
之前触发fetchCategories
。您需要从componentWillMount()
中删除this.props.dispatch(fetchPlaces())
,并将其添加到fetchPlaces()
的中,然后((响应)
,以确保在成功获取fetchPlaces()后触发
我认为默认情况下调度是同步的,所以它应该可以工作。但是,设置状态可能并不总是同步的。您是否尝试运行代码以查看它是否工作?@KeithA是的,在componentWillReceiveProps中,我正在检查nextProps是否同时具有这两个值,然后设置状态。您介意发布动作创建者和红色按钮吗ucer?谢谢@Rami Enbashi。