首页 > 解决方案 > 在构造函数中访问道具的正确方法是什么?

问题描述

在构造函数中访问道具的正确方法是什么?是的,我知道在 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', … }
    }
}

在某些情况下何时使用propsover this.props

标签: javascriptreactjsclassecmascript-6constructor

解决方案


this.props并且props在构造函数中可以互换,因为this.props === props只要传递propssuper. 使用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.需要删除即可。

在 TypeScript中也存在打字问题props,这this.props对于类型化组件来说更可取。


推荐阅读