【发布时间】:2019-02-15 18:32:51
【问题描述】:
那么为什么在这种情况下 react 调用会渲染:
class MyComponent extends React.Component {
constructor(props) {
this.state = {
user: { name: 'john' },
};
}
render() {
return (
<div>
Name: {this.state.user.name}
<button onClick={() => {
const user = this.state.user;
user.name = 'Michael';
// this works, also this.setState({}) with empty json works too
this.setState({ user });
}}> Change name </button>
</div>);
}
我所期望的是 React 不会检测到任何更改,并且为了让上述代码能够制作用户对象的副本,以便 React 检测到这样的更改:
const user = {...this.state.user}; // a new copy of object, so new refference
有什么想法吗?
【问题讨论】: