【问题标题】:Will setState inside componentWillReceiveProps run before render?componentWillReceiveProps 中的 setState 会在渲染之前运行吗?
【发布时间】:2017-12-01 20:32:05
【问题描述】:

react 文档提到对setState 的调用已排队,并且不会立即发生。 react 是否保证setStatecomponentWillReceiveProps 中排队将在下一个组件渲染之前执行?这两种情况中的任何一种都比另一种更有可能吗?

  1. props 更改 > componentWillReceiveProps 调用 > setState enqueued > setState 运行 > 渲染(包括新状态)

  2. props change > componentWillReceiveProps called > setState enqueued > render > setState runs > re-rendered

或者,这两种情况的可能性相同吗?意思是说 React 不做任何保证 setState 是否会相对于组件生命周期方法运行?

这是我的示例的 ES2015 代码摘录:

import React from 'react';

class Widget extends React.Component {

  componentWillReceiveProps() {
    this.setState({foo: 'bar'});
  }

  render() {
    return <div>
      <a onClick={(e) => {
        e.preventDefault();
        this.props.triggerExternalPropsChange();
      }}>
        Click me to trigger new props
      </a>
    </div>;
  }
}

triggerExternalPropsChange 将新的 props 传递给 Widget 组件。

【问题讨论】:

  • 这两种情况都有可能。无论状态是否已完成设置,您都应该始终设置渲染以成功完成。

标签: reactjs


【解决方案1】:

componentWillReceiveProps 存在的唯一原因是为组件提供setState 的机会。所以是的,您在其中同步设置的任何状态都将与新道具一起处理。在这种情况下不会有两个渲染,只有一个。

【讨论】:

  • this.setState({foo: 'bar'}) 根据facebook.github.io/react/docs/react-component.html#setstate 是异步的。如果我需要根据之前的状态和新的 props 改变状态,我该怎么办?使用更新函数不起作用,渲染只调用一次旧状态和新道具......
  • @Marcin “更新程序功能”是什么意思? Dan这里是说你可以在componentWillReceiveProps里面同步setState,在里面你可以访问next props,current props,当前state。
  • @Evan 根据 setState 文档,更新程序是箭头函数在:this.setState((prevState, props) =&gt; { return {counter: prevState.counter + props.step}; });。更多详情请查看github.com/facebook/react/issues/10111
  • @Marcin 你遇到了一些具体的问题吗? this.setState(...) 将在 componentWillReceiveProps() 中按预期工作。您无需做任何额外的事情。资料来源:我在 React 上工作。
  • @DanAbramov 我的问题是 JS 语法错误造成的。您可以在我上次评论的链接中查看更多详细信息。我很抱歉在这里产生噪音。
【解决方案2】:

是 1。

在 componentWillReceiveProps() 中调用 setState() 在组件渲染之前执行状态更新的意义上是一个例外,因此您将在同一个渲染中应用道具更改和状态更改。

【讨论】:

    【解决方案3】:

    是的,两者都有可能。 React 会在它获得新的 props 或 state 时尝试渲染,并且因为它确实 dom diffing,它会尝试尽可能频繁地渲染。不过,您可以选择控制它,使用 shouldComponentUpdate 您可以检查并等待道具和状态都更新后再渲染。

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多