[英]Can't use props from parent component in componentDidMount
I'm trying to send props
from parent component to child component.我正在尝试将props
从父组件发送到子组件。 I want to use this in componentDidMount()
at child component.我想在子组件的componentDidMount()
中使用它。 But it can't get this value.但是它不能得到这个值。 It can get this in render()
although.虽然它可以在render()
得到它。
parent component code:父组件代码:
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>
)
}
}
child component code:子组件代码:
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>
)
}
}
If you want to pass props to a child component, this is how you would do it.如果您想将 props 传递给子组件,您可以这样做。
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;
Now to use the props.现在来使用道具。 You do not need a class to use the props, but since that is what you were trying.你不需要一个类来使用道具,但因为那是你正在尝试的。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.