首页 > 解决方案 > TypeError:无法读取未定义的属性“RestaurantID”

问题描述

如何有条件地初始化某个状态的变量?

this.state = {
  RestaurantID:
    typeof this.props.location.state.RestaurantID !== 'undefined'
      ? this.props.location.state.RestaurantID
      : cookie.load('cookie'),
};

 componentDidMount() {
        axios.get(BASE_URL+`/rstProfile/${this.state.RestaurantID}`)
            .then((response) => {
            //update the state with the response data
            if(response.data.length !== 0) {
                this.setState({
                    RestaurantName: response.data[0].RestaurantName,
                    Email: response.data[0].Email,
                    Zipcode: response.data[0].Zipcode, 
              });
            }
        });
       

我的应用程序中有一条路线,可以由具有个人资料链接的人或自己访问用户个人资料。我试图像这样有条件地设置一个变量,但是得到了上面的类型错误。

标签: reactjserror-handlingstate

解决方案


您应该从状态声明中删除变量的赋值,并对 componentDidMount 进行条件赋值。这样可以防止在初始化期间依赖道具,因为不推荐这样做。

this.state = {
  RestaurantID: null,
};



componentDidMount() {
         console.log(this.props.location.state)
         const restaurantId = this.props.location.state.RestaurantID
        (!restaurantId) ? setState({ RestaurantID: cookie.load('cookie')}) : setState({RestaurantID: restaurantId})
        axios.get(BASE_URL+`/rstProfile/${this.state.RestaurantID}`)
            .then((response) => {
            //update the state with the response data
            if(response.data.length !== 0) {
                this.setState({
                    RestaurantName: response.data[0].RestaurantName,
                    Email: response.data[0].Email,
                    Zipcode: response.data[0].Zipcode, 
              });
            }
        });

还要确保您通过 props 收到的内容实际上已经到达,因为对于您收到的错误类型,它似乎不仅仅是 props 的问题,而是变量声明的问题。我建议在我的代码中使用 console.log,以便您可以从那里开始调试。


推荐阅读