为什么 React 浅层比较没有注意到引用的变化?



在reactjs.org中,在此页面https://fr.reactjs.org/docs/optimizing-performance.html,我不明白这个部分:

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方法中的单词数组,旧的和this.props.word的新值将被比较为相等,即使数组中的实际单词发生了变化。因此,单词列表不会更新,即使它有应该呈现的新词。

我从handleClick((中了解到,this.state.words在物理上发生了变化(以前的对象被新对象取代,所以是新指针(。一个肤浅的比较应该注意到它,因为它会注意到任何道具的内部变化,不是吗?为什么这里不是这样?

handleClick((,this.state.words物理上发生了变化(上一个对象被新对象替换,所以是新指针(

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

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在物理上发生了变化(上一个对象被新对象替换,因此新指针

没有。

第一行只是复制引用。CCD_ 3和CCD_。做一个words.push('marklar'),你会看到this.state.words.length也发生了变化。

const words = this.state.words;

当你之后做setState时,你只是";重写";state.wordswords,但这并没有真正起到任何作用;你保留相同的参考号。这基本上是一个反对。

相关内容

最新更新