gpt4 book ai didi

javascript - 无法将 Prop 传递给子组件中的 componentDidMount (React)

转载 作者:行者123 更新时间:2023-11-30 09:21:47 29 4
gpt4 key购买 nike

我在将 prop 传递给 React 应用程序的子组件中的 componentDidMount() 调用时遇到问题。

在我的 App.js 中,我通过 Router 传递 Prop ,如下所示:

App.js

class App extends Component {

state = {
city: ""
}

componentDidMount() {
this.setState({city: this.props.city});
}

render() {

return (
<div>
<Route path="/" exact render = {() => <Projections city={this.state.city} />} />
<Route path="/:id" component={FullPage} />
</div>
);
}

}

在我的 Projections.js 中,我有以下内容:

Projections.js

constructor(props) {
super(props);
this.state = {
location: this.props.city
}
}

componentDidMount () {
console.log(this.state.location);
console.log(this.props.city);

}

console.log(this.state);'返回一个空字符串。console.log(this.props.city);` 也返回一个空字符串。

但我需要在 componentDidMount() 中访问 city 属性的值。 console.log(this.props.city);render() 中返回 prop,但在 componentDidMount()

中不返回

为什么会这样,我如何在 componentDidMount() 中返回 props

最佳答案

在构造函数中你应该引用props,而不是this.props:

location: props.city

关于javascript - 无法将 Prop 传递给子组件中的 componentDidMount (React),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211188/

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