在渲染方法中反应无法读取this.props.location.state“

问题描述

我学习了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) 

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...