无法使用componentDidMount中父组件的道具

时间:2020-01-23 03:45:16

标签: javascript reactjs

我正在尝试将props从父组件发送到子组件。我想在子组件的componentDidMount()中使用它。但它无法获得此值。它可以在render()中获得。

父组件代码:

class Parent extends Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    // fetch with redux
    this.props.fetchItem(id);
  }

  renderItem() {
    const { item } = this.props;
    console.log("item", item);
    // item exists
    return <Child item={item} />
  }

  render() {
    return (
      <div>
       {this.renderItem()}
      </div>
    )
  }
}

子组件代码:

class Child extends Component {
  componentDidMount() {
    const { item } = this.props;
    console.log("item", item);
    // item doesn't exist
  }

  render() {
    console.log("item", item)
    // item exists
    return (
      <p>{item.name}</p>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

如果您想将道具传递给子组件,这就是您要这样做的方式。

import MyChildComponent from './itspath'; // import your child component

class Whatever extends React.Component {
    const name = "Bob";      // Pay attention this variable we will pass as props

    <MyChildComponent name={name} />   // Here name is now a prop
}
export default Whatever;

现在使用道具。您不需要使用类就可以使用道具,但是既然那样您就在尝试。

class MyChildComponents extends React.Component {
   componentDidMount() {
  const propsSent  = this.props.name;
  console.log(propsSent);     // This will get you the prop name with a value of Bob
}
}