React.js Recommended Assigning `props` Directly To State

半腔热情 提交于 2020-12-13 04:34:47

问题


A React.js warning was thrown:

IndexPage: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.

I had the following code:

    class IndexPage extends React.Component<IProps, IState> {
       constructor(props) {
          super(props)
          this.state = props
       }
    }

But, when I have changed my code to:

    class IndexPage extends React.Component<IProps, IState> {
       constructor(props) {
          super(props)
          this.state = {...props}
       }
    }

The warning's gone.

Can you please explain why?


回答1:


Because of how JS assignment of object values works, assigning one object to another means that the second variable will "point" to the same instance, or hold a reference to it:

let x = { v: 1 };
let y = x;
x.v = 2;
console.log(y.v) // prints "2"

The warning is there to prevent accidental assumptions about the props being automatically "propagated" to the state. IOW, it doesn't just work like you'd normally expect:

// assume props = { v: 1 };
this.state = props;
// now props changes to { v: 2 };
console.log(this.state.v) // still prints 1, and that's why you get the warning

The warning goes away because by destructuring, you're making it obvious that a new object is being created, and you don't expect the state to have the same value as props when they change.



来源:https://stackoverflow.com/questions/59877957/react-js-recommended-assigning-props-directly-to-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!