【问题标题】:React throws undefined error for an existing elementReact 为现有元素抛出未定义的错误
【发布时间】:2020-10-04 03:06:39
【问题描述】:

我正在尝试遍历一个数组并使用它的数据,但它返回了错误:

TypeError:无法读取未定义的属性“forEach”

这是日志的结果:

class Restockers extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
       ...
    }
  }

  render() {
    const rows = [];
    console.log('props: ', this.props); // this logs the content of props
    this.props.restockers.restockers.forEach(...)

  }
}

所以当代码中有this.props.restockers.restockers时,日志中只有this.props.restockers,它有一个空数组。

就像下一个截图:

所以我从代码中删除了额外的restockers。现在看看我的错误和我的日志:

我不明白这种奇怪的行为,现在在日志中是this.props.restockers.restockers,所以代码是错误的,因为它是this.props.restokers

如何解决?

【问题讨论】:

  • 不要相信控制台。它会更改数组的形状以使其更易于阅读,并且可以在运行时显示的数据更改时进行更新。请向我们展示您的道具是如何加载的,您是如何获取数据的?
  • 您是否厌倦了使用map
  • 打印this.props.restockers 而不是this.props。在两个控制台输出中都有一个对象 restockers 和一个 restockers 数组。所以this.props.restockers.restockers 确实为您提供了一个数组。看起来您最初创建了一个 restockers 对象并异步加载了 restockers 键。
  • 在你的问题中展示Restockers的父组件的实现会很有帮助。

标签: javascript arrays reactjs foreach


【解决方案1】:

您需要将一个元素数组传递给 jsx。问题是 forEach 不返回任何东西(即它返回未定义)。所以最好使用 map,因为它返回一个像这样的数组。

render() {
    const rows = [];
    console.log('props: ', this.props); // this logs the content of props
    this.props.restockers.restockers.map((restocker, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Restockerkey={i} restocker={restocker} />) 
        })

  }

【讨论】:

    猜你喜欢
    • 2017-08-05
    • 2017-08-14
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    相关资源
    最近更新 更多