gpt4 book ai didi

javascript - 无法在 componentDidMount 中使用父组件的 props

转载 作者:行者123 更新时间:2023-12-01 00:14:17 24 4
gpt4 key购买 nike

我正在尝试将 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>
)
}
}

最佳答案

如果您想将 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;

现在要使用 Prop 了。您不需要类来使用 Prop ,但因为这就是您正在尝试的。

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
}
}

关于javascript - 无法在 componentDidMount 中使用父组件的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59871305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com