问题:Action dispatch 在 Redux/React 中没有更新状态

我正在从组件调度一个动作,一切看起来都已正确链接,但是当我 console.log 组件道具中的状态时,它没有更新。

我尝试重新格式化我的代码并查看了多个示例,它看起来应该运行?当我从减速器登录时,它正在接收操作它只是没有更新状态。

    const mapStateToProps = state => ({
         todos: state
    });

    onSubmit(e) {
        e.preventDefault();
        let payload = this.state.content
        this.props.dispatch(post_todo(payload));
        console.log(this.props.todos)
        this.setState({
            content: ""
        })
    }
export default (
  state = [],
  action
) => {
  switch (action.type) {
    case POST_TODO:
      console.log("got it")
      console.log(action.payload)
      console.log(state)
      return [
        ...state,
        action.payload
      ];
    default:
      return state;
  }
};
export function post_todo (payload){
    return {
        type: POST_TODO,
        payload
    };
}

它应该将 props.todos 更新为正确的状态,但每次都显示一个空数组。

解答

onSubmit(e) {
    e.preventDefault();
    let payload = this.state.content
    this.props.dispatch(post_todo(payload)); <=== this line
    console.log(this.props.todos)
    this.setState({
        content: ""
    })
}

当你在我指向的那一行调度你的动作时,它会去执行你的动作,然后你可以在像componentWillReceiveProps这样的事件中接收到新更新的道具......

接收新的props到您的组件将导致您的组件重新render

所以,控制台记录你的道具执行你的动作之后,永远不会给你new state......在componentWillReceivePropsrender方法中等待它

这是一个如何在您的情况下获取新道具(待办事项)的示例:

componentWillReceiveProps(nextProps) {
  const { todos } = nextProps;

  console.log('I recieved new todos', todos);
}

此外,如果您的render方法呈现任何显示您从this.props.todos获取的todos字段的组件......也将自动更新......

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐