【发布时间】:2020-12-02 17:13:13
【问题描述】:
我学习了 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.,我会收到上述错误。
在我打电话给onImageClick 之前,this.props.location.state 不存在,我该如何处理这个问题
【问题讨论】:
-
您如何将道具发送到您的
<Component .../>?即<Component prop1=prop1var prop2=prop2var>? -
组件是一个图片库,只是等待道具知道要显示什么专辑。我把道具发到
onImageClick -
很高兴看到设置道具的代码,因为在调用道具时您会收到
undefined。另外,这个答案可能会对您有所帮助:How to set one component's state from another component in React
标签: reactjs react-props