【发布时间】:2018-07-06 13:11:44
【问题描述】:
我在我的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() 内返回道具,但不在 componentDidMount() 内
这是为什么以及如何在 componentDidMount() 内返回 props?
【问题讨论】:
-
您说第一个console.log 返回一个空字符串,然后第二个也没有返回任何内容。空字符串不是什么 ;) 尤其是当你这样做
state = { city: "" }
标签: javascript reactjs