【问题标题】:Action dispatch not updating state in Redux/React动作调度不更新 Redux/React 中的状态
【发布时间】:2019-08-15 01:43:33
【问题描述】:

我正在从组件调度一个动作,一切看起来都已正确链接,但是当我 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 更新到正确的状态,但每次都显示一个空数组。

【问题讨论】:

  • 如果您希望在this.props.dispatch(post_todo(payload)); 之后的下一行中的console.log(this.props.todos) 立即反映状态更改,那么它不会那样工作。您的组件必须经过一个更新循环。您应该会在下一次渲染调用中看到更新后的 this.props.todos

标签: javascript reactjs redux action


【解决方案1】:
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 方法中等待它

以下是如何在您的案例中获取新道具 (todos) 的示例:

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

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

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

【讨论】:

  • 那么我如何检查状态是否正确呈现
  • 天哪!太感谢了!我一直都做对了!
  • 很高兴它有帮助......快乐的编码!
  • 嘿@HendEl-Sahli 你能检查this 的问题吗?
猜你喜欢
  • 2018-05-23
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2019-12-04
  • 1970-01-01
相关资源
最近更新 更多