【问题标题】:React: Assigning State Passed as Prop to Component as Variable Prevents Update?反应:将作为道具传递给组件的状态作为变量分配防止更新?
【发布时间】:2017-08-07 09:24:37
【问题描述】:

假设我们有以下设置,父组件有两个子 C1 和 C2:

Example: container for C1 and C2, with a state called data

    -C1: input, updates state in Example through handler passed as propdisplay, shows state from Example
    -C2: display, shows state from Example

这里是代码和codepen:

class Example extends React.Component {
  constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }

  onUpdate (data) { this.setState({ data }) }

  render () {
    return (
      <div>
        <C1 onUpdate={this.onUpdate.bind(this)}/>
        <C2 data={this.state.data}/>
      </div>
    )
  }
}

class C1 extends React.Component {
    constructor(props) {
      super(props);
      this.onUpdate = this.props.onUpdate;
    }

    render () {
      return (
        <div>
          <input type='text' ref='myInput'/>
          <input type='button' onClick={this.update.bind(this)} value='Update C2'/>
        </div>
      )
    }

    update () {
      //this.props.onUpdate(this.refs.myInput.getDOMNode().value);
      this.onUpdate(this.refs.myInput.getDOMNode().value);
    }
}

class C2 extends React.Component {
    constructor(props) {
      super(props);
      this.data = this.props.data;
    }

    render () {
      return <div>{this.props.data}</div>
      //return <div>{this.data}</div>
    }
}

/*
 * Render the above component into the div#app
 */
React.render(<Example />, document.getElementById('app'));

请注意,在 C2 的构造函数中,我们引用了 this.props.data。如果我们将该变量设置为像this.data = this.props.data 这样的类属性,即使我们单击更新按钮并且示例的 this.state.data 已更改,React 也无法更新 C1。我已经注释掉了直接引用 this.props.data 的行。

我的第一个想法是这一定是 React 中的非法语法。但是,用 C1 进一步测试表明,如果传入的 props 是函数而不是状态,则没有问题(请参阅 C1 的update 函数下的代码以确认我在说什么)。

为什么这对作为 props 传入的 state 不起作用,而对作为 props 传入的函数起作用?我假设 Example 看到 C1 已更改 data 状态,因此,调用 C2 的重新渲染,它使用 this.data 来确定接下来要渲染的内容。

【问题讨论】:

    标签: javascript reactjs reactive-programming


    【解决方案1】:

    因为constructor 只被调用一次,而不是每次它获得新的状态或道具时,所以你的类变量引用最初传递的道具而不是新的道具,因为它不会再次重新运行构造函数。见constructor

    React 组件的构造函数在挂载之前被调用

    所以一旦它被挂载,它就不会再次被调用。另一方面,函数,尤其是纯函数,可以正常工作,因为您没有修改函数本身或其中的任何值。

    如果您想根据 props 更改更新类变量,您可能需要检查 shouldComponentUpdatecomponentWillReceiveProps

    因此,在您的 C2 组件中,要修复它,请使用以下代码:

    componentWillReceiveProps(nextProps) {
      this.data = this.nextProps.data
    }
    

    但我认为这样做是多余的,this.props 大部分时间都可以正常工作。

    【讨论】:

    • 我同意基于 props 设置状态是多余的。 React 实际上有一篇很棒的文章说这是一种反模式。这是另一个很好地解释它的stackoverflow。 stackoverflow.com/questions/28785106/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2020-01-08
    • 2017-11-19
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多