我读了丹写的article。在下面的示例中
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不会更改?
发布于 2019-03-07 06:03:25
props对象是不可变的,this.props引用可能会随着时间的推移而改变,以防收到新的属性。
它应该是:
handleClick = () => {
setTimeout(() => {
const { props } = this;
this.showMessage(props.user);
}, 3000);
};此外,应该跟踪超时,以便在组件卸载时取消,以防止泄漏和异常。
https://stackoverflow.com/questions/55032296
复制相似问题