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
相同的结果,它返回一个空字符串。所以这个精确的解决方案不起作用,但它让我找到了我的解决方案,我很快就会发布它