【问题标题】:Got this error: TypeError: Cannot read properties of undefined (reading 'map')收到此错误:TypeError: Cannot read properties of undefined (reading 'map')
【发布时间】:2022-01-16 02:57:04
【问题描述】:

我正在使用 Redux 构建一个反应项目。我遇到了这个奇怪的错误,我无法解决。

我在浏览器窗口中看到的错误:

Contacts.render
C:/Users/lenovo/Desktop/contactmanager_redux/src/components/contacts/Contacts.js:18
 

     15 | const { contacts } = this.props;
      16 | return (
      17 |   <React.Fragment>
    > 18 |     <h1 className="display-4 mb-2">
         | ^  19 |       <span className="text-success">Contact</span> List
      20 |     </h1>
      21 |     {contacts.map(contact => (

View compiled

▶ 22 stack frames were collapsed.

Function.mapToProps
C:/Users/lenovo/Desktop/contactmanager_redux/src/actions/contactActions.js:7
   

    4 | 
       5 | export const getContacts = () => async dispatch => {
       6 |   const res = await axios.get("https://jsonplaceholder.typicode.com/users");
    >  7 |   dispatch({
       8 |     type: GET_CONTACTS,
       9 |     paylaod: res.data
      10 |   });

View compiled

当我尝试使用 axios 获取数据并尝试在 reducer 文件中添加有效负载时出现此错误。我创建了单独的操作文件,然后使用 dispatch 函数将代码带到 reducer。

这是我的 Contacts.js 文件:

import React, { Component } from 'react';
import Contact from './Contact';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
// import {GET_CONTACTS} from '../../actions/types';
import {getContacts} from '../../actions/contactActions';

class Contacts extends Component {

  componentDidMount(){
    this.props.getContacts;
  }
  
  render() {
    const { contacts } = this.props;
    return (
      <React.Fragment>
        <h1 className="display-4 mb-2">
          <span className="text-success">Contact</span> List
        </h1>
        {contacts.map(contact => (
          <Contact key={contact.id} contact={contact} />
        ))}
      </React.Fragment>
    );
  }
}

Contacts.propTypes = {
  contacts: PropTypes.array.isRequired,
  getContacts: PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({
  contacts: state.contact.contacts
});

/*const mapDispatchToProps = (dispatch) => (
  {
    getContacts: () => (dispatch({type: GET_CONTACTS}))
  }
)*/

export default connect(mapStateToProps, getContacts)(Contacts);

我的 ContactActions.js 代码:

import {GET_CONTACTS, DELETE_CONTACT, ADD_CONTACT} from './types';
import axios from 'axios';


export const getContacts = () => async dispatch => {
  const res = await axios.get("https://jsonplaceholder.typicode.com/users");
  dispatch({
    type: GET_CONTACTS,
    paylaod: res.data
  });
}

export const deleteContact = (id) => {
  return {
    type: DELETE_CONTACT,
    payload: id
  }
}

export const addContact = (contact) => {
  return {
    type: ADD_CONTACT,
    payload: contact
  }
}

ContactReducer.js 代码:

    import {GET_CONTACTS, DELETE_CONTACT, ADD_CONTACT} from '../actions/types';

const initialState = {
  contacts: []
};

export default function(state = initialState, action){
  switch(action.type){
    case GET_CONTACTS:
      return {
        ...state,
        contacts: action.payload
      };

    case DELETE_CONTACT:
      return {
        ...state,
        contacts: state.contacts.filter(contact => contact.id !== action.payload)
      }

    case ADD_CONTACT:
      return {
        ...state,
        contacts: [action.payload, ...state.contacts]
      }

    default:
      return state;
  }
}

【问题讨论】:

  • contacts 可能是未定义的,所以contacts.map 爆炸了。相关:您没有在 componentDidMount 中调用 getContacts
  • @rayhatfield 我已经使用 this.props.getContacts 调用了 getContacts
  • 没有括号你就不会调用它。
  • 在您的问题中,ContactReducer.jsContactActions.js 中的代码是相同的。
  • 如果this.props.getContacts 是一个函数,您可以使用parens/args 调用它,例如this.props.getContacts()。如果你不了解这种基本的 javascript,那么构建一个 React/Redux 应用程序将会很困难。

标签: reactjs redux react-redux


【解决方案1】:

最初联系人将没有数据。像这样进行条件渲染,因此只有当联系人中有数据时才会进行渲染。

{contacts && contacts.map(contact => (
          <Contact key={contact.id} contact={contact} />
        ))}

【讨论】:

  • 这个方法没有错误,但是我还是没有得到数据
【解决方案2】:

您的Contacts 组件存在几个问题:

1- 既然您已经评论了mapDispatchToProps,实际上您还没有将getContacts 函数作为道具发送到您的Contacts 组件。

2- 你还没有在componentDidMount 中调用getContacts。你刚刚写了this.props.getContacts;getContacts 必须是一个函数,你必须调用它才能获取数据。

我稍微编辑了你的MyContact.js文件,请试试这个:

MyContact.js

import React, { Component } from 'react';
import Contact from './Contact';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
// import {GET_CONTACTS} from '../../actions/types';
import {getContacts as fetchContacts} from '../../actions/contactActions';

class Contacts extends Component {

  componentDidMount(){
    this.props.getContacts();
  }

  render() {
    const { contacts = [] } = this.props;
    return (
      <React.Fragment>
        <h1 className="display-4 mb-2">
          <span className="text-success">Contact</span> List
        </h1>
        {contacts.map(contact => (
          <Contact key={contact.id} contact={contact} />
        ))}
      </React.Fragment>
    );
  }
}

Contacts.propTypes = {
  contacts: PropTypes.array.isRequired,
  getContacts: PropTypes.func.isRequired
}

const mapStateToProps = (state) => ({
  contacts: state.contact.contacts
});

const mapDispatchToProps = (dispatch) => (
  {
    getContacts: () => (dispatch(fetchContacts())
  }
)

export default connect(mapStateToProps, mapDispatchToProps)(Contacts);

【讨论】:

  • 我正在使用单独的操作和减速器文件来处理调度功能。这就是为什么我在 Contacts.js 中评论 this.props.getContacts() 我也使用了这个,但我不知道为什么它会出错。当我不使用括号时,错误不会出现。
  • 错误是什么?如果没有mapDispatchToPropsgetContacts 属性将是未定义的,并且调用它会导致错误undefined is not a function。你的错误信息是一样的吗?
  • 请看一下contactActions.js,我已经定义了getContacts()函数并将其导入Contacts.js。现在我已经解决了这个错误,但我仍然没有从 API 获取我想要的数据
  • 是的,你在contactActions.js文件中定义了getContacts,但是由于你需要访问dispatch,所以你应该把它用作中间件,如果你直接调用getContacts,你就不用'无权调度。
  • 我这里使用了connect() 将组件连接到redux store。在我的 store.js 中,我使用了 applyMiddleware() 来使用中间件。其实我已经解决了这个问题。非常感谢您的帮助。
【解决方案3】:

试试这个。

{contacts?.map(contact => (
      <Contact key={contact.id} contact={contact} />
    ))}

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 2021-12-31
    • 2021-11-10
    • 2021-11-08
    • 2022-12-16
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多