【发布时间】:2019-02-04 20:07:57
【问题描述】:
最近我在使用 React/Redux (Thunk) 时遇到了一个棘手的问题:我已经用 Action 和 Reducer 正确地创建了我的 Store,在我的组件中我触发了 componentDidMount 方法中的 Async 函数以更新状态,但是状态似乎没有改变,尽管它在 componentDidUpdate 和 mapStateToProps 函数中发生了变化!为什么 ?这是我的代码:
export const getAllInterventions = () => {
return dispatch => {
dispatch(getAllDataStart());
axios.get('/interventions.json')
.then(res => {
dispatch(getAllDataSuccess(res.data));
})
.catch(err => {
dispatch(getAllDataFail(err));
});
};
我的减速机:
case actionTypes.GET_ALL_INTERVENTIONS_SUCCESS:
return {
...state,
interventions: interventions: action.interventions
};
我的组件:
componentDidMount() {
this.props.getAllInterventions();
console.log('DidMount: ', this.props.inter); /*Empty Array Or Undefined */
}
const mapStateToProps = state => {
console.log('mapStateToProps', state);
return {
inter: state.interventions,
error: state.error
};
【问题讨论】:
-
case actionTypes.GET_ALL_INTERVENTIONS_SUCCESS: return { ...state, 干预:interventions: action.interventions };请检查reducer中的上述代码我认为应该是干预:action.interventions
-
不抱歉,我打错了,我已经尝试了所有操作,但我遇到了同样的问题,我认为组件在请求完成之前完成安装
-
我认为您需要某种微调器或指示器来显示未解决的承诺。你可以使用一些变量来喜欢 loading:true 并在你的减速器中将它设置为 false 一旦解决。在渲染函数中使用相同的加载来显示微调器。
-
我用过redux devtool,我发现状态有所有数据,但是组件在第一次调用时无法接收到完整状态,直到didUpdate!!!!!!跨度>
标签: reactjs redux react-redux axios redux-thunk