【问题标题】:When do i need to pass prop to constructor of a react component using super(props)? [duplicate]我什么时候需要使用 super(props) 将 prop 传递给 react 组件的构造函数? [复制]
【发布时间】:2016-11-26 14:38:25
【问题描述】:

很多时候我们在构造函数中发送 props,但我们从不在构造函数的任何地方使用 this.props,所以为什么需要传递它以及何时需要传递。

 class App extends React.Component {

      constructor(props) {
        super(props);    // When do we need to send props to the constructor
        this.state = {
           data: 'Initial data...'
        }
        this.updateState = this.updateState.bind(this);
      };

      updateState(e) {
          this.setState({data: e.target.value});
      }

      render() {
        return (
           <div>
             <input type = "text" value = {this.state.data} 
              onChange = {this.updateState} />
             <h4>{this.state.data}</h4>
          </div>
        );
      }

   }

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    React.Component 构造函数实际上不需要道具。您可以编写此代码,一切正常:

    constructor() {
        super();
        this.state = {
           data: 'Initial data...'
        };
        this.updateState = this.updateState.bind(this);
      };
    

    这是因为构造函数路径实际上并不是在标准 React 生命周期中分配道具的位置。 React.Component 实际上并不使用 props,只设置 this.props 以防您的构造函数需要使用它。但通常你不应该在你的构造函数中使用props,因为使用props to initialize your state is an anti-pattern

    如果你已经配置了 babel,你甚至不需要构造函数来处理这样的事情:

    class MyComponent extends React.Component {
        state = { data: "initial data" };
    
        updateState = (arg1, arg2) => { ... };
    
        // instead of:
        // updateState(arg1, arg2) { ... }
    
    }
    

    【讨论】:

    • 是用简单的 state = {} 表达式替换 constructor() 来设置初始状态,在使用 ES2015 时被认为是一种好习惯?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2016-10-19
    • 2018-05-06
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多