【发布时间】:2020-04-03 08:59:11
【问题描述】:
我有 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
});
我想在调用/search api 时使用这些valueCategory 和valueCity。
代码:
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>
);
}
}
我的问题是:
- 我可以通过
render()方法访问{this.props.location.valueCity.name} - 但我无法在
componentDidMount()或任何其他方法中访问相同的内容?我要崩溃了
TypeError: 无法读取未定义的属性“名称”
【问题讨论】:
-
您的位置在渲染时是否可访问或已获取?
-
componentDidMount 将在第一次渲染后立即被调用。所以可能是您的网络需要一些时间来加载数据......但是,您尝试访问数据是 api 调用权的结果?...尝试在访问对象属性之前添加检查..例如: const { location = {} } = this.props;常量 {valueCity = {} } = 位置 || {};常量 {name = {}} = valueCity || {}。或者你可以使用 lodash get
-
@RajeshKumaran 不,我不想访问 API 结果。我正在尝试访问从顶级组件传递的
props。直到现在我还没有调用 API。 -
@MaciejTrojniarz 位置可通过
render()方法访问 -
该错误是由于您的道具在 location 中没有名为 valueCity 的键。
标签: reactjs react-component zomato-api