简体   繁体   English

React无法读取undefined的属性映射

[英]React cannot read property map of undefined

I am very new to react and I am trying to bring in data from a rails api but I am getting the error TypeError: Cannot read property 'map' of undefined 我很新的反应,我试图从rails api引入数据,但我收到错误TypeError: Cannot read property 'map' of undefined

If i use the react dev tools I can see the state and I can see the contacts if I mess around with it in the console using $r.state.contacts Can someone help with what I have done wrong? 如果我使用react开发工具,我可以看到状态,如果我在控制台中使用$r.state.contacts搞砸了,我可以看到联系人。有人可以帮助我做错了吗? my component looks like this: 我的组件看起来像这样:

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? 无法读取属性'map'的undefined,为什么?

Because this.state is initially {} , and contacts of {} will be undefined . 因为this.state最初是{} ,而{} contacts将是未定义的 Important point is, componentDidMount will get called after initial rendering and it is throwing that error during first rendering. 重要的是, componentDidMount将在初始渲染后调用,并在首次渲染时抛出该错误。

Possible Solutions: 可能的解决方案:

1- Either define the initial value of contacts as [] in state: 1-将contacts的初始值定义为[]状态:

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

2- Or put the check before using map on it: 2-或者在使用map之前进行检查:

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

For checking array, you can also use Array.isArray(this.state.contacts) . 对于检查数组,您还可以使用Array.isArray(this.state.contacts)

Note: You need to assign unique key to each element inside map, check the DOC . 注意:您需要为地图内的每个元素指定唯一键,检查DOC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM