reactjs - 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,
});
}
});
我的应用程序中有一条路线,可以由具有个人资料链接的人或自己访问用户个人资料。我试图像这样有条件地设置一个变量,但是得到了上面的类型错误。
解决方案
您应该从状态声明中删除变量的赋值,并对 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,以便您可以从那里开始调试。
推荐阅读
- ios - FloatingPanel 没有出现 - Swift Xcode
- javascript - Keystonejs V5 搜索与 GraphQL 的关系
- javascript - 当 Promise 已经运行时,Promise.all 是否比单独的 await 语句更快?
- python - 多年时间序列在python中具有阴影范围
- python - Python新手问题:为什么执行代码后数据不显示
- php - 如何防止 Laravel 6.x 队列调度程序多次尝试相同的作业 ID?
- python - 无法将文件下载到 AWS Lambda
- java - 有没有办法创建可以移动的隐形浮动盔甲架(Spigot API)?
- javascript - 为什么 Javascript 中的新数组没有被我得到的结果推送?
- javascript - Google Apps 在 onEdit 函数中编写多个 IF 语句