【问题标题】:React.js Recommended Assigning `props` Directly To StateReact.js 推荐将 `props` 直接分配给状态
【发布时间】:2020-05-09 16:33:09
【问题描述】:

引发了 React.js 警告:

IndexPage:不建议将 props 直接分配给 state,因为对 props 的更新不会反映在 state 中。大多数情况下,直接使用 props 会更好。

我有以下代码:

    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}
       }
    }

警告消失了。

你能解释一下原因吗?

【问题讨论】:

  • 这也解决了我的问题。

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


【解决方案1】:

由于对象值的 JS 赋值是如何工作的,将一个对象分配给另一个意味着第二个变量将“指向”同一个实例,或者持有对它的引用:

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

警告是为了防止意外假设道具被自动“传播”到状态。 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

警告消失了,因为通过解构,您可以明显看出正在创建一个新对象,并且您不希望状态在更改时与道具具有相同的值。

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 2019-07-23
    • 2023-01-11
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2022-01-01
    相关资源
    最近更新 更多