I'm having issues passing a prop to a ponentDidMount()
call in a child ponent on my React
application.
In my App.js
I am passing props via Router
like below:
App.js
class App extends Component {
state = {
city: ""
}
ponentDidMount() {
this.setState({city: this.props.city});
}
render() {
return (
<div>
<Route path="/" exact render = {() => <Projections city={this.state.city} />} />
<Route path="/:id" ponent={FullPage} />
</div>
);
}
}
In my Projections.js I have the following:
Projections.js
constructor(props) {
super(props);
this.state = {
location: this.props.city
}
}
ponentDidMount () {
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.
But I need to access the value of the city
prop within ponentDidMount()
. console.log(this.props.city);
within render()
returns the prop, but not in ponentDidMount()
Why is this and how do I return props
within ponentDidMount()
?
I'm having issues passing a prop to a ponentDidMount()
call in a child ponent on my React
application.
In my App.js
I am passing props via Router
like below:
App.js
class App extends Component {
state = {
city: ""
}
ponentDidMount() {
this.setState({city: this.props.city});
}
render() {
return (
<div>
<Route path="/" exact render = {() => <Projections city={this.state.city} />} />
<Route path="/:id" ponent={FullPage} />
</div>
);
}
}
In my Projections.js I have the following:
Projections.js
constructor(props) {
super(props);
this.state = {
location: this.props.city
}
}
ponentDidMount () {
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.
But I need to access the value of the city
prop within ponentDidMount()
. console.log(this.props.city);
within render()
returns the prop, but not in ponentDidMount()
Why is this and how do I return props
within ponentDidMount()
?
-
2
You say that the first console.log returns an empty string, then the second one return nothing as well. An empty string is not nothing ;) Especially when you do
state = { city: "" }
– sjahan Commented Jul 6, 2018 at 13:15
2 Answers
Reset to default 3In the constructor you should reference props
, not 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. And it gets called only once in a ponent lifecycle.
You can use ponentWillReceiveProps
to get props whenever it receive and update state accordingly.
Inside Projections.js
UNSAFE_ponentWillReceiveProps(nextProps){
if(nextProps.city){
this.setState({location:nextProps.city})
}
}
Here is working codesand