【问题标题】:Iterating over array inside object in JSX giving undefined在JSX中迭代对象内部的数组给出未定义
【发布时间】:2020-01-23 03:42:10
【问题描述】:

我正在从我的 API 获取数据:

  fetch('/api/p/' + project_id).then(res => res.json())
            .then((project) => {
                console.log(project)
                this.setState({ project })
            }
            );

项目结构是这样的:

{
 name: "project1",
comments: ["com1", "com2"]
}

现在在我的返回函数中,我需要遍历所有 cmets 并在不同的行上将每个评论谨慎地呈现出来,所以我使用了以下代码:

this.state.project.comments.map((comment) => {
           return (
               <p><i class="fas fa-chevron-right"></i> { comment } </p>
          );
 });

我收到此错误:

TypeError: Cannot read property 'map' of undefined

我尝试了 map 或 forEach 和 for。而且我也无法得到它的长度,因为我得到了同样的错误。

但是如果我输入this.state.project.comments,我会在一行中得到所有元素,没有空格,就像comment1comment2comment3

【问题讨论】:

    标签: javascript json reactjs jsx


    【解决方案1】:

    您正在尝试.map 的值是undefined。这可能是因为 this.state.project.comments 在你 fetching 时没有定义,但 React 仍在尝试进行初始渲染。

    确保在某处设置初始状态,例如

    constructor() {
      super();
    
      this.state = { project: { comments: [] } };
    }
    

    或者,您可以在调用 .map 时在此处提供默认值:

    (this.state.project.comments || []).map((comment) => {
    

    【讨论】:

    • 谢谢你,这解决了问题..我认为它只是有点未定义
    【解决方案2】:

    我认为你映射错了这一行,这一行: this.state.comments.map((comment) =&gt; { 应该 this.state.project.comments.map((comment) =&gt; {

    【讨论】:

    • 我修好了,不是那样的
    【解决方案3】:

    从您的代码中我可以看到,您正在映射“cmets”,但您正在更新项目,而且您也必须喜欢

    this.setState({
      project: res.data
    })
    

    用于映射数据

    this.state.project.map((project)=>{
       return (
                   <p><i class="fas fa-chevron-right"></i> { project.comments } </p>
              );
    })
    

    【讨论】:

    • 项目是一个对象,不是数组
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多