我在将 prop 传递给应用程序componentDidMount()子组件中的调用时遇到问题React。
在我中,App.js我通过Router如下方式传递props:
应用程序.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 中,我有以下内容:
投影.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);` 也返回一个空字符串。
但是我需要访问city.prop的值componentDidMount()。console.log(this.props.city);内render()返回props,但不在componentDidMount()
这是为什么,我如何回报props之内componentDidMount()?