抛出了 React.js 警告:
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
}
}
但是,当我将代码更改为:
class IndexPage extends React.Component<IProps, IState> {
constructor(props) {
super(props)
this.state = {...props}
}
}
警告消失了。
您能解释一下原因吗?
最佳答案
由于 JS 对象值赋值的工作方式,将一个对象分配给另一个对象意味着第二个变量将“指向”同一个实例,或保存对其的引用:
let x = { v: 1 };
let y = x;
x.v = 2;
console.log(y.v) // prints "2"
该警告是为了防止意外假设 Prop 会自动“传播”到状态。 IOW,它并不像您通常期望的那样工作:
// 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 具有相同的值。
关于reactjs - React.js 建议直接将 `props` 分配给状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59877957/