渲染方法中的 React 无法读取 this.props.location.state”

React in render method cant read this.props.location.state"

我学习了 React,但现在我不知道该怎么做 我得到:

Cannot read property 'state' of undefined

上线:

  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 不存在

How can I handle this since this.props.location.state don't exist before I call onImageClick

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)