0

我有一个Restaurants组件负责从 Zomato Dev API 中列出餐厅。我已经从其他组件传递到Category组件。CityRestaurants

我正在Restaurants使用以下代码打开组件:

this.props.history.push(
        {
            pathname : '/restaurants', 
            valueCategory : this.props.location.valueA,  // CATEGORY
            valueCity : this.state.cities[index] // CITY
        });

我想使用这些valueCategoryvalueCity调用/searchapi。

代码 :

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:无法读取未定义的属性“名称”

4

1 回答 1

0

你试过componentDidUpdate生命周期方法吗?比较传入此方法的道具

        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;
       }

**检查并告诉我

于 2019-12-10T10:01:33.983 回答