reactjs - React.js 建议直接将 `props` 分配给状态

标签 reactjs warnings react-props react-component react-state

抛出了 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/

相关文章:

javascript - AsyncStorage不保存更改状态 - React Native

javascript - Material-UI useMediaQuery 最初没有识别正确的断点

java - 无法阻止 ant 生成编译器 Sun 专有 API 警告

javascript - 如何检查reactjs映射中的未定义

reactjs - 将 localStorage.getItem() 与 typescript 一起使用

multithreading - {DCC 警告} W1036 变量 '$frame' 可能尚未初始化?

iphone - Xcode - 警告问题

javascript - 将 React prop 传递到 axios.post 时如何绑定(bind) "this"

javascript - 无法访问从父级作为 props 传递的数组 - React

javascript - React.js 子组件不更新从 props 派生的样式,为什么? (样式组件)