【问题标题】:this.setState() does not work in componentWillReceivePropsthis.setState() 在 componentWillReceiveProps 中不起作用
【发布时间】:2017-02-20 13:55:15
【问题描述】:

我有一个登录页面,我在其中使用componentWillReceiveProps 路由到下一页。但是我在componentWillReceiveProps 中设置的state 似乎没有设置。

这是我的componentWillReceiveProps 方法:

  componentWillReceiveProps(nextProps) {
      if (nextProps.isAuthenticated === true) {
          browserHistory.push('/home');
      } else {
        console.log("this.props :::" + JSON.stringify(this.props))
          console.log("this.state :::" + JSON.stringify(this.state))
          console.log("nextProps :::" + JSON.stringify(nextProps))
          this.setState({
              errorMessage: nextProps.authenticationError
          })
          console.log("this.state :::" + JSON.stringify(this.state))
      }
  }

我得到的console output 是这样的:

this.props :::{"authenticationError":null}  
this.state :::{"username":"35135","password":"3135","errorMessage":""}  
nextProps :::{"isAuthenticated":false,"authenticationError":"Could not find user in DB."}  
this.state :::{"username":"35135","password":"3135","errorMessage":""}  

这里即使设置了状态,我的状态也没有改变。

请告诉我我做错了什么。

编辑:我有这个组件是 ErrorText ,它接受 errroMessage 属性。

<ErrorText errorMsg={this.state.errorMessage}></ErrorText>

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    setState() is an asynchronous operation,所以不会立即生效:

    setState() enqueues 更改组件状态并告诉 React 该组件及其子组件需要使用更新后的状态重新渲染 [...]

    将setState() 视为更新组件的请求而不是立即命令。为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。 React 不保证立即应用状态更改。

    setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用setState() 之后立即阅读this.state 是一个潜在的陷阱。相反,请使用 componentDidUpdate 或 setState 回调 [...],它们都保证在应用更新后触发。

    以下是您的上下文中的 setState 回调示例:

    this.setState(
        { errorMessage: nextProps.authenticationError },
        function() {
            console.log( 'this.state ::: ' + JSON.stringify( this.state ) );
        }
    );
    

    【讨论】:

    • 如果我使用componentDidUpdate,它会再次渲染组件吗?
    • 您应该在componentDidUpdate 或render 中检查新状态。大致意思是:刚刚调用setState之后状态没有更新。
    • 实际上我的用例是这样的:如果找到我的用户,我会重定向,如果没有,我会在我的状态下设置错误消息。我确信componentWillReceiveProps 会再次渲染。但我想知道componentDidUpdate update 是否会自己做render,还是应该使用forceUpdate() 或类似的东西。
    • 是的,阅读文档:facebook.github.io/react/docs/…
    【解决方案2】:

    参考同样的stackoverflow问题:

    Why Calling react setState method doesnt mutate the state immediately

    setState() 不会立即改变 this.state 而是创建一个 等待状态转换。调用 this 后访问 this.state 方法可能会返回现有值。没有 保证对 setState 的调用和调用的同步操作可能 进行批处理以获得性能提升。

    【讨论】:

      【解决方案3】:

      这可能是因为 this.setState 是一个异步函数。您可以传递回调来处理设置状态后应该直接发生的事件。结帐this为代码示例选择的答案。

      【讨论】:

        猜你喜欢
        • 2020-04-12
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 2019-01-03
        相关资源
        最近更新 更多