Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - 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

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? 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cannot read property 'map' of undefined, Why?

Because this.state is initially {}, and contacts of {} will be undefined. Important point is, componentDidMount will get called after initial rendering and it is throwing that error during first rendering.

Possible Solutions:

1- Either define the initial value of contacts as [] in state:

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

2- Or put the check before using map on it:

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

For checking array, you can also use Array.isArray(this.state.contacts).

Note: You need to assign unique key to each element inside map, check the DOC.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...