簡體   English   中英

React如何使用const props = this.props捕獲道具

[英]How does React capture the props with `const props = this.props`

我讀了丹寫的文章 在下面的示例中

class ProfilePage extends React.Component {
  showMessage = (user) => {
    alert('Followed ' + user);
  };

  handleClick = () => {
    const props = this.props;
    setTimeout(() => this.showMessage(props.user), 3000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

為什么this.props更改時props不會更改,因為它們都指向同一個引用?

props對象是不可變的,如果接收到新的props, this.props引用可能會隨着時間而變化。

它應該是:

  handleClick = () => {
    setTimeout(() => {
      const { props } = this;
      this.showMessage(props.user);
    }, 3000);
  };

另外,應跟蹤超時以在組件卸載時取消該超時,以防止泄漏和異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM