I don"t quite understand what I saw when I was learning react by myself. Can you explain.
this can be a problem if the props and state properties have more complex data structures. For example, let"s write a ListOfWords component to show a comma-separated list of words, and in the parent component WordAdder, you add a word to the list when you click a button. The following code does not work correctly:
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() {
//
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>
);
}
}
The problem with is that PureComponent only makes pre-comparisons between the old this.props.words and the new this.props.words. So the handleClick code in the WordAdder component mutates the words array. Although the actual values in the array have changed, the old this.props.words and the new this.props.words values are the same, and even if the ListOfWords needs to render the new values, they will not be updated.
Power of immutable data
the easiest way to avoid such problems is not to mutate the value of (mutate) props or state. For example, the above handleClick method can be overridden by using concat:
handleClick() {
this.setState(prevState => ({
words: [...prevState.words, "marklar"],
}));
};