React 无法读取未定义的 属性 映射

React cannot read property map of undefined

我对反应还很陌生,我正在尝试从 rails api 导入数据,但我收到错误 TypeError: Cannot read property 'map' of undefined

如果我使用 React 开发工具,我可以看到状态,如果我使用 $r.state.contacts 在控制台中弄乱它,我可以看到联系人,有人可以帮助我做错什么吗?我的组件如下所示:

import React from 'react';
import Contact from './Contact';

class ContactsList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  componentDidMount() {
    return fetch('http://localhost:3000/contacts')
      .then(response => response.json())
      .then(response => {
        this.setState({
          contacts: response.contacts
        })
      })
      .catch(error => {
        console.error(error)
      })
  }

  render(){
    return(
     <ul>
        {this.state.contacts.map(contact => { return <Contact contact{contact} />})}
      </ul>
    )
  }
}

export default ContactsList;

Cannot read property 'map' of undefined, Why?

因为 this.state 最初是 {}{}contacts 将是 undefined。重要的一点是,componentDidMount 将在初始渲染后被调用,并且它在第一次渲染期间抛出该错误。

可能的解决方案:

1-要么将contacts的初始值定义为[] in state:

constructor(props) {
  super(props)
    this.state = {
       contacts: []
    }
}

2- 或者在使用 map 之前打勾:

{this.state.contacts && this.state.contacts.map(....)

检查数组,也可以使用Array.isArray(this.state.contacts).

注意:你需要为map中的每个元素分配唯一的键,检查DOC.