У меня есть компонент Restaurants
, который отвечает за перечисление ресторанов из API Zomato Dev. Я передал 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: Невозможно прочитать имя свойства неопределенного
props
, переданному из компонента верхнего уровня. Я до сих пор не вызывал API. - person Kushal   schedule 10.12.2019render()
- person Kushal   schedule 10.12.2019console.log("Component Did Mount Restaurant : " + this.props);
вcomponentDidMount()
, он печатаетComponent Did Mount Restaurant : [object Object]
- person Kushal   schedule 10.12.2019