简体   繁体   English

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

[英]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? 为什么this.props更改时props不会更改,因为它们都指向同一个引用?

props object is immutable, this.props reference may change with time in case new props are received. props对象是不可变的,如果接收到新的props, this.props引用可能会随着时间而变化。

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. 另外,应跟踪超时以在组件卸载时取消该超时,以防止泄漏和异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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