React无法读取undefined的属性映射 [英] React cannot read property map of undefined
问题描述
我很反应,我正在尝试从rails api引入数据,但我收到错误 TypeError:无法读取未定义的属性'map'
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
如果我使用react dev工具,我可以看到状态,如果我在控制台中使用 $搞砸了联系人,我可以看到它们r.state.contacts
有人可以帮助我做错了吗?我的组件如下所示:
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;
推荐答案
无法读取属性' map'of undefined,为什么?
Cannot read property 'map' of undefined, Why?
因为 this.state
最初是 {}
和的联系
{}
将未定义即可。重要的是, componentDidMount 将在初始渲染后调用,并在首次渲染时抛出该错误。
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.
可能的解决方案:
1-在状态中将 contacts
的初始值定义为 []
:
1- Either define the initial value of contacts
as []
in state:
constructor(props) {
super(props)
this.state = {
contacts: []
}
}
2-或者在使用<$ c之前进行检查$ c>地图:
{this.state.contacts && this.state.contacts.map(....)
对于检查数组,你也可以使用 Array.isArray(this.state.contacts)
。
For checking array, you can also use Array.isArray(this.state.contacts)
.
注意:你需要要为地图中的每个元素指定唯一键,请检查 DOC 。
Note: You need to assign unique key to each element inside map, check the DOC.
这篇关于React无法读取undefined的属性映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!