【问题标题】:Why does react call render function if I have not changed the reference of the state? [duplicate]如果我没有更改状态的引用,为什么 React 会调用渲染函数? [复制]
【发布时间】: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

有什么想法吗?

【问题讨论】:

    标签: reactjs state


    【解决方案1】:

    使用空对象设置状态是有效的,因为 react 不会对状态突变本身做任何事情。相反,它只是使用状态对象并在调用渲染方法时创建更新的虚拟 DOM,这也反映了状态突变。

    但是,进行状态突变的问题在于,生命周期方法现在无法清楚地区分 prevState 和 this.state,并且由于 prevState 和 this.state 值将导致很多比较失败两者都引用相同的引用。

    【讨论】:

    • 很好的解释!
    猜你喜欢
    • 2021-07-11
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多