Javascript 无法将道具传递到子组件中的组件DidMount(React)
将道具传递给Javascript 无法将道具传递到子组件中的组件DidMount(React),javascript,reactjs,Javascript,Reactjs,将道具传递给componentDidMount()调用我的React应用程序上的子组件时遇到问题 在我的App.js中,我通过路由器传递道具,如下所示: App.js class App extends Component { state = { city: "" } componentDidMount() { this.setState({city: this.props.city}); } render() { return ( <div
componentDidMount()
调用我的React
应用程序上的子组件时遇到问题
在我的App.js
中,我通过路由器传递道具,如下所示:
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>
);
}
}
constructor(props) {
super(props);
this.state = {
location: this.props.city
}
}
componentDidMount () {
console.log(this.state.location);
console.log(this.props.city);
}
UNSAFE_componentWillReceiveProps(nextProps){
if(nextProps.city){
this.setState({location:nextProps.city})
}
}
console.log(this.state);'返回空字符串。
console.log(this.props.city);`同时返回一个空字符串
但是我需要访问componentDidMount()
中的city
属性的值<代码>控制台.log(this.props.city)在render()中的code>返回道具,但在componentDidMount()中不返回
这是为什么?我如何在componentDidMount()
中返回props
?在构造函数中,您应该参考props
,而不是this.props
:
location: props.city
在构造函数中,您应该参考props
,而不是此.props
:
location: props.city
这里有工作
您可以说第一个console.log返回一个空字符串,然后第二个console.log也不返回任何内容。空字符串不是零;)特别是当您执行state={city:'}
时,您会说第一个console.log返回一个空字符串,然后第二个console.log也不返回任何内容。空字符串不是零;)特别是当您执行state={city:'}
时,谢谢您,但在控制台上仍然返回null。log@logos_164哪一行返回的null
?您确定返回的值是null
?在JavaScript中,null
、undefined
和'
不是一回事。当我console.log(this.state.location)
中componentDidMount()
是App.js
中定义的this.props.city
吗?如果没有,它将覆盖您在构造函数中设置的空字符串。是的,它是从index.js
传递的,谢谢,但在控制台上仍然返回null。log@logos_164哪一行返回的null
?您确定返回的值是null
?在JavaScript中,null
、undefined
和'
不是一回事。当我console.log(this.state.location)
中componentDidMount()
是App.js
中定义的this.props.city
吗?如果没有,它将覆盖您在构造函数中设置的空字符串。是的,它是从index.js
中传递的,谢谢,但我仍然得到了与状态相同的结果,它返回一个空字符串。因此,这个精确解不起作用,但它使我找到了我最终开始工作的解决方案,我会尽快发布,谢谢你,但是我仍然得到了与state
相同的结果,它返回一个空字符串。所以这个精确的解决方案不起作用,但它让我找到了我的解决方案,我很快就会发布它