【问题标题】:Why can't I access default props in react constructor, but I can in render?为什么我不能在反应构造函数中访问默认道具,但我可以在渲染中访问?
【发布时间】:2017-04-25 18:42:20
【问题描述】:

根据标题,为什么最初的 this.props 失败了?更实际的是,如果您依赖构造函数中的道具,您如何解决这个问题?例如,我想在我的订阅中引用道具?

class AboutBox extends Component {
  static defaultProps = {
    title: 'Undefined Product',
  }
  constructor() {
    super();
    console.log(this.props.title); //this fails (=> null)
  }
  render() {
    console.log(this.props.title); //this works (=> 'Undefined Product')
    return null;
  }
}

【问题讨论】:

标签: reactjs meteor ecmascript-6


【解决方案1】:

你必须把道具放在构造函数的args上,然后把它们传递给super

constructor(props){
    super(props);
    console.log(props.title);
}

在构造函数中使用道具,这也可以,但是在针对 IE 的编译中存在一些问题

【讨论】:

    【解决方案2】:

    尝试向constructor() 参数和super() 调用添加道具:

    constructor(props) {
      super(props);
      console.log(props.title);
    }
    

    【讨论】:

      【解决方案3】:

      如果要在构造函数中使用this.props,则需要将props 传递给super()。否则,没关系,因为 React 在调用构造函数后立即从外部为实例设置了.props

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-21
        • 1970-01-01
        • 2017-10-10
        • 1970-01-01
        • 2019-07-09
        • 2011-05-06
        • 1970-01-01
        相关资源
        最近更新 更多