【问题标题】:console.log(this.props) undefinedconsole.log(this.props) 未定义
【发布时间】:2020-06-04 21:28:52
【问题描述】:

在我的代码中,当我未定义时,我在 componentDidMount 中使用了 console.log(this.props)。我在 render() 中的 console.log(this.props) 得到了四个输出,前两个所有属性都未定义,后两个是正确的。

componentDidMount = () => {
        const { ratingsAverage } = this.props;
        console.log(ratingsAverage);
        //this.setState({value: this.props.ratingsAverage})
    }

render() {
        console.log(this.props);
 }

console.log(ratingsAverage) 在 componentDidMount() 中的输出是未定义的。

console.log(this.props) 在 render() 中的输出如下图所示

【问题讨论】:

  • componentDidMount 只被调用一次,如果它们是通过异步方法来的,那么你的道具可能是未定义的。而每次更改道具时都会执行渲染。一切似乎工作正常。您在这里遇到什么问题?
  • 我的问题是如何在子组件的 componentDidMount 中获取道具?

标签: reactjs


【解决方案1】:

试试这个。你的组件构造函数应该是这样的

constructor(props){
  super(props);
  this.state = {
     //states
  };
}

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2020-03-31
    • 2016-11-23
    • 1970-01-01
    • 2022-01-22
    • 2014-04-18
    相关资源
    最近更新 更多