【问题标题】:"Cannot read property 'map' of undefined" ReactJS and Lodash array“无法读取未定义的属性 'map'” ReactJS 和 Lodash 数组
【发布时间】:2018-03-16 19:40:32
【问题描述】:

我正在尝试使用下面的方法将一个数组渲染到下面的 JSX 中;

const events = this.state.event.map((item, i) => {

我可以渲染出数组,但它会为每个数组重复渲染函数。我只希望它输出 id 等于 1 的那个。尝试实现 Lodash _.find 时,我可以使用它在控制台中渲染出数组;

const firstArray = _.find(this.state.event, function(o) { return o.id == 1; });
console.log(firstArray);

以下是我在渲染方法中实现 Lodash 的尝试,但是当我运行它时出现以下错误;

未捕获的类型错误:无法读取未定义的属性“地图”

下面是组件中的代码

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from "jquery";
import lodash from "lodash";
import api from "../api.js";    

export default class EventRequest extends React.Component {
constructor(props) {
  super(props);

  this.state = {event: []};
}

componentDidMount() {
  this.EventGroup();
}
EventGroup() {

  return  $.getJSON(api.eventRequest).then((data) => {
    console.log(data);
    this.setState({ event: data.results });
  });
}

render() {
    const events = _.find(this.state.event, ['id', 1 ]).map((item, i) => {
    return <div>
    <div className="center-cards margin-top margin-bottom test-cardSecond">
      <div className="text-center margin-top">
        <h1 className="card-heading">Scottish Conference 2017</h1>
        <div className="card-sub">
          <div>{item.description}</div><br />
        </div>
      </div>
    </div>
      <div className="belowBoxTestSecond">
        <h1 className="bodyHeading">Example</h1>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. <br /><br />
        Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. <br />
        Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. <br />
        Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? <br /><br />
        Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
      </div>
    </div>
  });

  return <div id="" className="">
    <div>{ events }</div>
  </div>
}
}

【问题讨论】:

    标签: javascript arrays reactjs lodash


    【解决方案1】:

    我不知道错误的原因,也无法复制它,因为我无法让 _.find() 运行,但是您不需要 lodash:

    const events = this.state.event.filter(e => e.id === 1).map(...);
    

    编辑:我检查了 lodash 文档,错误的原因是 _.find 不返回数组/空数组,它返回一个对象/未定义。 lodash 确实有一个 _.filter 方法,它可能会起作用。

    【讨论】:

    • 感谢克里斯,这非常有效。非常感谢!
    【解决方案2】:

    这应该可以解决问题:

    const events = this.state.data.filter(data => data.id === 1).map(item => <div>{item.name}</div>;
    

    您收到Cannot read property 'map' of undefined 的原因是您的数据没有被提取,而您尝试映射它。

    您可以将loading 标志设置为如下状态:

    this.state = {event: [], loading: true};
    

    在 fetch 完成后在 EventGroup 函数中设置它是 false:

    this.setState({ event: data.results, loading: false });
    

    然后在render方法中:

    render(){
        if(this.state.loading){
             return <LoadingComponent />
        }
    
        // The rest of the code which will render if the data is fetched
    }
    

    Here is the fiddle.

    【讨论】:

      【解决方案3】:

      尝试将import lodash from "lodash" 更改为import _ from "lodash"

      【讨论】:

      • 不幸的是,这并没有解决问题,我仍然遇到同样的错误。
      • 我假设 API 调用是异步的。如果是这样,则页面可能在数据返回之前呈现。首先,添加this.EventGroup = this.EventGroup.bind(this)构造函数。其次,尝试在componentWillMount() 中调用this.EventGroup() 而不是componentDidMount()。这行得通吗?
      • @223seneca 除了错误之外,this.state.event 开始时是 [ ],它应该与期望数组的渲染方法完美配合。该问题与异步 API 调用无关。
      猜你喜欢
      • 2017-08-15
      • 2018-03-25
      • 2022-07-11
      • 2022-07-27
      • 1970-01-01
      • 2016-08-08
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多