React.js 推荐直接将 `props` 分配给 State [英] React.js Recommended Assigning `props` Directly To State
问题描述
引发了 React.js 警告:
A React.js warning was thrown:
IndexPage:不建议将 props 直接分配给 state,因为 props 的更新不会反映在 state 中.大多数情况下,直接使用props比较好.
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.
我有以下代码:
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}
}
}
警告消失了.
你能解释一下原因吗?
推荐答案
由于 JS 对象值赋值的工作原理,将一个对象赋值给另一个对象意味着第二个变量将指向"同一个实例,或者持有一个引用给它:
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"
警告是为了防止对道具自动传播"到状态的意外假设.IOW,它并不像您通常期望的那样工作:
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
警告消失了,因为通过解构,您很明显正在创建一个新对象,并且您不希望状态在更改时具有与 props 相同的值.
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.
这篇关于React.js 推荐直接将 `props` 分配给 State的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!