我有一个Restaurants
组件负责从 Zomato Dev API 中列出餐厅。我已经从其他组件传递到Category
组件。City
Restaurants
我正在Restaurants
使用以下代码打开组件:
this.props.history.push(
{
pathname : '/restaurants',
valueCategory : this.props.location.valueA, // CATEGORY
valueCity : this.state.cities[index] // CITY
});
我想使用这些valueCategory
并valueCity
调用/search
api。
代码 :
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>
);
}
}
我的问题是:
- 我可以通过
{this.props.location.valueCity.name}
方法render()
访问 - 但是我无法以
componentDidMount()
任何其他方法访问相同的内容?我要崩溃了
TypeError:无法读取未定义的属性“名称”