React cannot read property map of undefined

后端 未结 1 808
萌比男神i
萌比男神i 2020-12-09 12:23

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

相关标签:
1条回答
  • 2020-12-09 12:42

    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.

    0 讨论(0)
提交回复
热议问题