简体   繁体   中英

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

I read the article written by Dan. In the example below

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

Why props does not change when this.props changed, since both point to the same reference?

props object is immutable, this.props reference may change with time in case new props are received.

It should be:

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

Also, timeouts should be tracked to be cancelled at component unmount in order to prevent leaks and exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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