在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ 不要突變(mutate) props 或 state 的值是什么意思

不要突變(mutate) props 或 state 的值是什么意思

在自學react的時候看到這么一段話 不太明白。能解釋一下么。
如果 props 和 state 屬性存在更復雜的數(shù)據(jù)結構,這可能是一個問題。例如,我們編寫一個 ListOfWords 組件展現(xiàn)一個以逗號分隔的單詞列表,在父組件 WordAdder ,當你點擊一個按鈕時會給列表添加一個單詞。下面的代碼是不能正確地工作:

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>
    );
  }
}

問題是 PureComponent 只進行在舊的 this.props.words 與新的 this.props.words 之間進行前比較。因此在 WordAdder 組件中 handleClick 的代碼會突變 words 數(shù)組。雖然數(shù)組中實際的值發(fā)生了變化,但舊的 this.props.words 和新的 this.props.words 值是相同的,即使 ListOfWords 需要渲染新的值,但是還是不會進行更新。
不可變數(shù)據(jù)的力量
避免這類問題最簡單的方法是不要突變(mutate) props 或 state 的值。例如,上述 handleClick 方法可以通過使用 concat 重寫:

handleClick() {
  this.setState(prevState => ({
    words: [...prevState.words, 'marklar'],
  }));
};
回答
編輯回答
青裙

就是下面這些代碼有問題

const words = this.state.words;
words.push('marklar');
this.setState({words: words});

應該寫成

const words = [...this.state.words];
words.push('marklar');
this.setState({words: words});

也就是說要修改一個Array或Object時,應該先clone一個出來,然后再setState回去
不然React不知道你改沒改,React不是通過復雜比較來監(jiān)聽state的變化的

2017年7月31日 05:47