TypeError:无法读取属性'地图'react redux中未定义的

TypeError: Cannot read property 'map' of undefined in react-redux

本文关键字:redux react 未定义 地图 读取 属性 TypeError      更新时间:2023-09-26

我是React和Redux的新手,仍然有点困惑。

我的目标是使用GET请求在HTML中呈现一堆json数据。我使用react和redux来管理对象的状态,但我相信我的问题是数据甚至不在中

所以基本上,每当有人请求URL/课程时,他/她都会在json中看到一堆数据。

我在组件中得到错误

TypeError:无法读取未定义的属性"map"

这是代码

行动

export function getCourses() {
  return (dispatch) => {
    return fetch('/courses', {
      method: 'get',
      headers: { 'Content-Type', 'application/json' },
    }).then((response) => {
      if (response.ok) {
        return response.json().then((json) => {
          dispatch({
            type: 'GET_COURSES',
            courses: json.courses
          });
        })
      }
    });
  }
}

还原剂

export default function course(state={}, action) {
  switch (action.type) {
    case 'GET_COURSES':
      return Object.assign({}, state, {
        courses: action.courses
      })
    default:
      return state;
  }

}

组件

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';

class Course extends React.Component {

  allCourses() {
    return this.props.courses.map((course) => {
      return(
        <li>{ course.name }</li>
      );
    });
  }
  render() {
    return (
      <div>
        <ul>
          { this.allCourses() }
        </ul>
      </div>
    )
  }
}
const mapStateToProps = (state) => {
  return {
    courses: state.courses
  }
}
export default connect(mapStateToProps)(Course);

索引减少器,在这里我组合所有

import { combineReducers } from 'redux';
import course from './course';
export default combineReducers({
  course,
});

配置存储,在这里我存储初始状态和还原

import { applyMiddleware, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
  const store = createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(thunk),
      typeof window == 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
    )
  );
  return store;
}

我相信为什么没有数据是因为我没有采取行动?任何帮助都将不胜感激。

mapStateToProps将根状态作为参数(您的索引减少器,也是根减少器),而不是course减少器。据我所知,这是你们商店的结构:

-index <- This is the root reducer
  -course

因此,要获得该州的课程,请在您的组件中:

// state is the state of the root reducer
const mapStateToProps = (state) => {
  return {
    courses: state.course.courses
  }
}

此外,您可能会考虑使用一个空的课程数组初始化course reducer的状态,因此,如果必须在启动操作之前渲染组件,则不会出现错误。

const initialState = {
    courses: []
};
export default function course(state= initialState, action) {
    ...
}

最后,你根本没有启动操作,所以你永远不会真正得到课程,我想你希望在加载Course组件后检索它们,这样你就可以在组件中使用componentDidMount事件。

首先,您需要将操作映射到组件的属性

// Make sure you import the action
import { getCourses } from './pathToAction';
...
const mapDispatchToProps = (dispatch) => {
  return {
    onGetCourses: () => dispatch(getCourses())
  };
}
// Connect also with the dispatcher
export default connect(masStateToProps, mapDispatchToProps)(Course);

现在当组件装载时调用onGetCourses属性

class Course extends React.Component {
    componentDidMount() {
      this.props.onGetCourses();
    }
    ...
}

这是因为道具有时可能是未定义的,所以您必须编写这样的条件

allCourses() {
     if(this.props.courses){
    return this.props.courses.map((course) => {
      return(
        <li>{ course.name }</li>
      );
    });
   }
   else {
   return []; 
  }