[英]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;
无法读取属性'map'的undefined,为什么?
因为this.state
最初是{}
,而{}
contacts
将是未定义的 。 重要的是, componentDidMount将在初始渲染后调用,并在首次渲染时抛出该错误。
可能的解决方案:
1-将contacts
的初始值定义为[]
状态:
constructor(props) {
super(props)
this.state = {
contacts: []
}
}
2-或者在使用map
之前进行检查:
{this.state.contacts && this.state.contacts.map(....)
对于检查数组,您还可以使用Array.isArray(this.state.contacts)
。
注意:您需要为地图内的每个元素指定唯一键,检查DOC 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.