[英]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.