问题描述
我学习了React,现在我不知道该怎么做:
无法读取未定义的属性“状态”
在线:
if (album.route === this.props.location.state.week) {
这是渲染器:
render() {
let photosArr = []
albums.map((album) => {
if (album.route === this.props.location.state.week) {
album.data.forEach((photo) => {
photosArr.push([photo.id,photo.src])
})
}
})
this.state.items = photosArr
console.log(this.props.location)
我用import { withRouter } from "react-router";
这样称呼它:
onImageClick = val => {
const {history} = this.props;
history.push("/timeLineViewer",val);
};
如果我删除了albums.map((album..
代码,那么console.log....
就会显示道具谷了。
问题是rendered
在我调用从onImageClick
更新道具之前被调用,因此如果我有this.props.location.state.week.
,我会收到上述错误。
如何处理此问题,因为在致电this.props.location.state
之前onImageClick
不存在
解决方法
由于在调用onImageClick之前this.props.location.state不存在,我该如何处理
Javascript引发错误,因为您试图获取未定义的属性。因此,您应该处理未定义的情况。
替换:
if (album.route === this.props.location.state.week)
具有:
if (album.route === this.props.location?.state?.week)
或:
if (this.props.location &&
this.props.location.state &&
album.route === this.props.location.state.week)