【问题标题】:React in render method cant read this.props.location.state"渲染方法中的反应无法读取 this.props.location.state”
【发布时间】: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


【解决方案1】:

我该如何处理这个问题,因为 this.props.location.state 在我调用 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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2016-10-30
    • 2015-07-03
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多