React 无法读取未定义的属性映射

2024-04-21

我对反应很陌生,我正在尝试从 Rails api 引入数据,但我收到了错误TypeError: Cannot read property 'map' of undefined

如果我使用反应开发工具,我可以看到状态,如果我在控制台中使用它,我可以看到联系人$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”,为什么?

Because this.state最初是{}, and contacts of {}不明确的。重要的一点是,组件已挂载 https://facebook.github.io/react/docs/react-component.html#componentdidmount将在初始渲染后被调用,并且在第一次渲染期间抛出该错误。

可能的解决方案:

1- 定义初始值contacts as []处于状态:

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

2- 或在使用前检查map on it:

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

为了检查数组,您还可以使用Array.isArray(this.state.contacts).

Note:您需要为地图内的每个元素分配唯一的键,检查DOC https://facebook.github.io/react/docs/lists-and-keys.html#keys.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 无法读取未定义的属性映射 的相关文章

随机推荐