繁体   English   中英

为什么 React 浅比较不会注意到引用的变化?

[英]Why doesn't React shallow comparisons notice references' changes?

In reactjs.org, at this page https://fr.reactjs.org/docs/optimizing-performance.html , I don't understand this part:

class ListOfWords extends React.PureComponent {
  render() {
    return <div>{this.props.words.join(',')}</div>;
  }
}

class WordAdder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      words: ['marklar']
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // This section is bad style and causes a bug
    const words = this.state.words;
    words.push('marklar');
    this.setState({words: words});
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick} />
        <ListOfWords words={this.state.words} />
      </div>
    );
  }
}

问题是 PureComponent 会在 this.props.words 的新旧值之间做一个简单的比较。 由于此代码更改了 WordAdder 的 handleClick 方法中的 words 数组,因此 this.props.words 的旧值和新值将比较相等,即使数组中的实际单词已更改。 ListOfWords 因此不会更新,即使它有应该呈现的新词。

我从handleClick() 中了解到,this.state.words 物理变化(之前的object 被替换为新的,所以新的指针)。 浅比较应该注意到它,因为它会注意到任何道具的内部变化,不是吗? 为什么不是这里的情况?

handleClick(),this.state.words物理变化(之前的object换成新的,所以新指针)

这不是真的。 我们来看看这个方法的作用:

handleClick() {
  // This section is bad style and causes a bug
  const words = this.state.words; // words is now a reference to the array
  words.push('marklar'); // we add an item to the array. reference doesn't change
  setState({words: words}); // we update state setting words to the same array reference
}

现在,在下一次重新渲染时,react 比较先前的words数组和新words数组,它发现数组引用是相同的。

“浅比较”不检查数组内的内容。 它检查引用以查看它是否是新的

this.state.words 物理变化(之前的object换成新的,所以新指针

它没有。

第一行只是复制参考。 this.state.wordswords都指向同一个数组。 执行words.push('marklar')你会看到this.state.words.length发生了变化。

const words = this.state.words;

当您之后执行setState时,您只需用words “覆盖” state.words ,但这并没有真正做任何事情; 你保持相同的参考。 它本质上是无操作的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM