【问题标题】:What is the correct way to access props in the constructor?在构造函数中访问道具的正确方法是什么?
【发布时间】:2019-03-30 22:18:59
【问题描述】:

在构造函数中访问 props 的正确方法是什么?是的,我知道在 React 文档中是这样说的

在实现 React.Component 子类的构造函数时,你 应该在任何其他语句之前调用 super(props)。否则, this.props 将在构造函数中未定义,这可能会导致错误

更清楚地说,如果我们可以在构造函数中使用道具,为什么我们需要this.props

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(props)
        // -> { something: 'something', … }
        // absolutely same
        console.log(this.props)
        // -> { something: 'something', … }
    }
}

在某些情况下使用props 而不是this.props

【问题讨论】:

    标签: javascript reactjs class ecmascript-6 constructor


    【解决方案1】:

    正确的方法是 - 不要在你的构造函数中使用 props - 只是发送到一个父级。

    但两种方式都可以。

    因此,在构造函数中读取 props 有一种特殊情况,它是从 props 设置的默认状态。

    在调用 super(props) 之后的构造函数中 this.props 和 props 等于this.props = props.

    它只是关于你喜欢什么,我更喜欢总是打电话给this.props

    例子:

       constructor(props) {
            super(props)
            this.state = {
               isRed: this.props.color === 'red',
            }
       }
    

    请确保您在构造函数的第一行调用super(props)

    【讨论】:

    • 所以如果我想使用 props 设置默认状态,我应该怎么做?
    【解决方案2】:

    此建议的存在是为了防止您通过从构造函数调用对象上的其他方法来引入错误,这些方法依赖于this.props。您不想明确地将道具传递给这些。

    例如以下将是一个错误,因为您在super 之前调用了doStuff

    class MyComponent extends React.Component {    
        constructor(props) {
            this.doStuff()
            super(props)
        }
    
        doStuff() {
          console.log("something is: " + this.props.something)
        }
    }
    

    【讨论】:

    • 我知道这一点,我以前从未在构造函数中调用过方法。我只是想知道propsthis.props在构造函数中有什么区别,哪个是最好的选择?
    • 没有区别
    【解决方案3】:

    this.propsprops 在构造函数中可以互换,因为this.props === props只要将props 传递给super。使用this.props 可以立即检测到错误:

    constructor() {
      super();
      this.state = { foo: this.props.foo }; // this.props is undefined
    }
    

    一致使用this.props 可以更轻松地重构构造函数主体:

    constructor(props) {
      super(props);
      this.state = { foo: this.props.foo };
    }
    

    state = { foo: this.props.foo };
    

    只有this. 需要删除。

    还有typing problems with props in TypeScript,这使得this.props更适合类型化组件。

    【讨论】:

    • 你需要复制 foo 吗?在 state 和 props 中保存相同的对象并不是一个好主意。为什么?
    • @JaLe 因为状态可能会独立于道具而改变。需要设置 initial 状态,有时它可能以某种方式依赖于 initial 道具,它们不一定像示例中一样。
    • 这样说是真的。
    • 但是当你写入这个 foo 时要小心,你可以改变(静音)道具。
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多