问题
I have Restaurants
component which is responsible for listing restaurants from Zomato Dev APIs. I have passed Category
and City
from other components to Restaurants
component.
I am opening Restaurants
component with below code :
this.props.history.push(
{
pathname : '/restaurants',
valueCategory : this.props.location.valueA, // CATEGORY
valueCity : this.state.cities[index] // CITY
});
I want to use these valueCategory
and valueCity
in calling /search
api.
Code :
class Restaurants extends React.Component {
constructor(props) {
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
this.getRestaurants = this.getRestaurants.bind(this);
}
componentDidMount() {
// I AM GETTING ERROR 'TypeError: Cannot read property 'name' of undefined' ON THIS LINE
console.log("Component Did Mount Restaurant : " + this.props.location.valueCity.name);
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log("Component Did Update :", prevProps);
//THIS PRINTS prevProps, WHICH CONTAINS valueCity and valueCategory but I am unable to access them
return false;
}
render() {
let category, city;
category = '';
city = '';
if(!isUndefined(this.props.location.valueCategory)) {
category = <p>You selected Category as : {this.props.location.valueCategory.categories.name}</p>;
}
if(!isUndefined(this.props.location.valueCity)) {
// STRANGLY, THIS LINE WORKS FINE! WHEN I AM ACCESSING valueCity.name
city = <p>You selected City as : {this.props.location.valueCity.name}</p>;
}
console.log(this.props.location);
return (
<div>
{category}
{city}
</div>
);
}
}
My question is :
- I am able to access
{this.props.location.valueCity.name}
inrender()
method - But I am not able to access the same in
componentDidMount()
or any other method? I am getting crash
TypeError: Cannot read property 'name' of undefined
回答1:
Have you tried componentDidUpdate life cycle method? compare the props incoming to this method
this.state={
valueCategory:"",
valueCity:"" //you can chose any data type,
checker:true
}
this.stateUpdater(prevProps){
let valueCategory={this.props};
let valueCity={this.props};
if(this.props.valueCategory===undefined){/*check the data
what is incoming and use condition accrodingly*/
this.setState({valueCategory:prevProps.location.valueCategory
,checker:false})
}else{
//no update
this.setState({checker:false})
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log("see the props",prevProps,this.props);
if(this.state.checker)
this.stateUpdater(prevProps);
else{
console.log("do nothing")
}
return false;
}
**check and let me know
来源:https://stackoverflow.com/questions/59262734/not-able-to-use-props-to-query-api-in-react-js