[英]Trouble passing props to componentDidMount in child component (React)
我在将React
传递给我的React
应用程序的子组件中的componentDidMount()
调用时遇到问题。
在我的App.js
我通过Router
传递道具,如下所示:
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);' returns an empty string.
console.log(this.props.city);`也会返回一个空字符串。
但是我需要在componentDidMount()
访问city
道具的值。 console.log(this.props.city);
在render()
返回prop,但在componentDidMount()
不返回
为什么会这样,如何在componentDidMount()
返回props
?
在构造函数中,您应该引用props
,而不是this.props
:
location: props.city
<Route path="/" exact render = {() => <Projections city={this.state.city} {...this.props} />} />
尝试在路线中传递其余道具
这是因为您在constructor
中分配的道具在那个时间可能会或可能不会收到实际值。 而且它在组件生命周期中仅被调用一次。 您可以使用componentWillReceiveProps
每当它接收并更新状态时获取道具。
内部Projections.js
UNSAFE_componentWillReceiveProps(nextProps){
if(nextProps.city){
this.setState({location:nextProps.city})
}
}
这是工作代码和
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.