【问题标题】:TypeError: Cannot read property 'map' of undefined, in react hooks crud applicationTypeError:无法读取未定义的属性“地图”,在反应挂钩 crud 应用程序中
【发布时间】:2020-03-16 07:54:45
【问题描述】:

我正在使用 React.js 开发一个简单的 crud 应用程序,当我尝试显示我从中获得的事件列表时,我遇到了这个问题:“TypeError: Cannot read property 'map' of undefined” :http://127.0.0.1:8000/api/events(以 json 格式显示事件列表)。

代码如下:

import React, { Component } from 'react';
import Event from './Event';
import axios from 'axios';

class DisplayEvent extends Component {
  constructor(props) {
    super(props);
    this.state = { value: '', events: '' };
  }
  onDelete = id => {
    // console.log("event list ", id);
    this.props.onDelete(id);
  };

  onEdit = id => {
    // console.log("event list ", id);
    this.props.onEdit(id);
  };

  componentDidMount() {
    axios.get('http://127.0.0.1:8000/api/events')
      .then(response => {
        this.setState({ events: response.data });
      })
      .catch(function (error) {
        console.log(error);
      })
  };



  render() {
    const events = this.props.events;
    return (
      <div>
        <h1>Events</h1>




        <table className="table table-hover">
          <thead>
            <tr>
              <td>ID</td>
              <td>Event Name</td>
              <td>Event Description</td>
              <td width="200px">Actions</td>
            </tr>
          </thead>
          <tbody>
            {events.map(event => {
              return (
                <Event
                  key={event.id}
                  event={event}
                  onDelete={this.onDelete}
                  onEdit={this.onEdit}
                />
              )
            })}

          </tbody>
        </table>
      </div>
    )
  }
}
export default DisplayEvent;

【问题讨论】:

    标签: javascript reactjs laravel react-hooks crud


    【解决方案1】:

    您应该使用 state 而不是 props,因为您将 API 响应设置为您的 state

      render() {
        const { events } = this.state;
        ...
    

    【讨论】:

    • 老实说,状态和道具仍然让我感到困惑,谢谢!我改变了你提到的代码,它说:TypeError:events.map is not a function
    • @AlaBenAicha 那你可能需要检查状态是否是一个数组
    【解决方案2】:
    1. events 设置为状态上的空数组
    2. 从 state 而不是 props 中读取事件:
    3. (可选)使用loading 状态显示加载器并确定何时获取数据。
    class DisplayEvent extends Component {
      constructor(props) {
        super(props);
        this.state = { value: '', loading: true, events: [] }; // use array here
      }
    
      componentDidMount() {
        this.setState({ loading: true });
        axios
          .get('http://127.0.0.1:8000/api/events')
          .then(response => {
            this.setState({ events: response.data, loading: false });
          })
          .catch(function(error) {
            console.log(error);
            this.setState({loading: false});
          });
      }
    
      render() {
        const { events, loading } = this.state; // get events from the state
        return (
          <div>
            <h1>Events</h1>
            <table className="table table-hover">
              <thead>
                <tr>
                  <td>ID</td>
                  <td>Event Name</td>
                  <td>Event Description</td>
                  <td width="200px">Actions</td>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <p>Loading events...</p>
                ) : (
                  events.map(event => {
                    return <Event key={event.id} event={event} onDelete={this.onDelete} onEdit={this.onEdit} />;
                  })
                )}
              </tbody>
            </table>
          </div>
        );
      }
    }
    
    

    【讨论】:

    • 你好@Clarity我现在收到这个错误:未处理的拒绝(TypeError):无法读取未定义的属性'setState'
    • 如果中了catch,改成箭头函数.catch((error) =&gt; { console.log(error); this.setState({loading: false}); });
    【解决方案3】:

    如果API返回的数据为undefined,则设置一个空数组为events。现在您还没有添加条件来处理这种情况。如果您从不是数组的响应中获得 undefined 值,这就是它显示此错误的原因。

            this.setState({ events: response.data || [] });
    

      componentDidMount() {
        axios.get('http://127.0.0.1:8000/api/events')
          .then(response => {
            this.setState({ events: response.data || [] });
          })
          .catch(function (error) {
            console.log(error);
          })
      };

    更新

    const events = this.props.events || [];
    

    【讨论】:

    • 我修改了你提到的代码,但它仍然返回:TypeError: events.map is not a function
    • 我已经更新了答案。还需要检查是否不是数组,赋值数组值,请查看更新后的答案。
    猜你喜欢
    • 2021-04-12
    • 2020-06-30
    • 2019-09-04
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2021-03-14
    • 2021-08-28
    相关资源
    最近更新 更多