简体   繁体   English

无法将道具传递给子组件中的componentDidMount(反应)

[英]Trouble passing props to componentDidMount in child component (React)

I'm having issues passing a prop to a componentDidMount() call in a child component on my React application. 我在将React传递给我的React应用程序的子组件中的componentDidMount()调用时遇到问题。

In my App.js I am passing props via Router like below: 在我的App.js我通过Router传递道具,如下所示:

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>
    );
}

}

In my Projections.js I have the following: 在我的Projections.js中,我具有以下内容:

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);` returns an empty string as well. console.log(this.props.city);`也会返回一个空字符串。

But I need to access the value of the city prop within componentDidMount() . 但是我需要在componentDidMount()访问city道具的值。 console.log(this.props.city); within render() returns the prop, but not in componentDidMount() render()返回prop,但在componentDidMount()不返回

Why is this and how do I return props within componentDidMount() ? 为什么会这样,如何在componentDidMount()返回props

在构造函数中,您应该引用props ,而不是this.props

location: props.city
        <Route path="/" exact render = {() => <Projections city={this.state.city} {...this.props} />} />

Try passing rest of props in route 尝试在路线中传递其余道具

this is because you assigned props in constructor that time it may or may not receive actual value. 这是因为您在constructor中分配的道具在那个时间可能会或可能不会收到实际值。 And it gets called only once in a component lifecycle. 而且它在组件生命周期中仅被调用一次。 You can use componentWillReceiveProps to get props whenever it receive and update state accordingly. 您可以使用componentWillReceiveProps每当它接收并更新状态时获取道具。

Inside Projections.js 内部Projections.js

UNSAFE_componentWillReceiveProps(nextProps){
   if(nextProps.city){
     this.setState({location:nextProps.city})
   }
}

Here is working codesand 这是工作代码和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM