TypeError: Cannot read property 'events' of undefined

TypeError: Cannot read property 'events' of undefined

我一直在尝试创建一个类似待办事项的应用程序,但在这里我添加了一个事件,而不是待办事项,我可以在其中创建、删除和查看没有更新部分的事件。我已经设置了我的动作、减速器、存储文件。为了设置一个假 api,我使用了 json-server。后端数据的格式类似于 {posts:[id, title, place]}。但是,当我 运行 我的文件时,我收到错误 TypeError: Cannot read property 'events' of undefined。我需要 运行 应用程序的帮助。我还设置了一个 codesandbox 来查看整个项目

Events.js

import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import EventItem from './EventItem';
import EventForm from './EventForm';
import { getEvents } from '../../actions/events';

const Events = ({ getEvents, event: { events } }) => {
  useEffect(() => {
    getEvents();
  }, [getEvents]);

  return (
    <Fragment>
      <h1 className="large text-primary">Posts</h1>
      <p className="lead">
        <i className="fas fa-user" /> Your Events
      </p>
      <EventForm />
      <div className="posts">
        {events.map((event) => (
          <EventItem key={event.id} event={event} />
        ))}
      </div>
    </Fragment>
  );
};

Events.propTypes = {
  getEvents: PropTypes.func.isRequired,
  event: PropTypes.object.isRequired
};

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

export default connect(mapStateToProps, { getEvents })(Events);

action.js

import {CREATE_EVENT, GET_EVENTS, DELETE_EVENT } from "./types";
import api from '../utils/api';
export const getEvents = () => async dispatch => {
    try {
      const res = await api.get('/posts');
  
      dispatch({
        type: GET_EVENTS,
        payload: res.data
      });
    } catch (err) {
      console.log(err)
    }
  };

  export const deleteEvent =(id)=>async dispatch=>{
      try{
          await api.delete(`/posts/${id}`)
          dispatch({
              type: DELETE_EVENT,
              payload: id
          })
      }catch(err){
          console.log(err)
      }
  }


  // Add post
export const createEvent = formData => async dispatch => {
    try {
      const res = await api.post('/posts', formData);
  
      dispatch({
        type: CREATE_EVENT,
        payload: res.data
      });
  
      
    } catch (err) {
      console.log(err)
    }
  };

reducer.js

import {CREATE_EVENT, GET_EVENTS, DELETE_EVENT} from "../actions/types";

const initialState={
    events: [],
    }

export default function(state=initialState, action){
    const {type, payload} = action;
    switch(type){
        case GET_EVENTS: 
            return {
                ...state,
                events: payload,
     
        
            };
        case CREATE_EVENT:
            return {
                ...state,
                events: [payload, ...state.events],
            };
        case DELETE_EVENT:
            return {
                ...state,
                events: state.events.filter(event=>event.id !==payload),
            };
        default:
            return state;
    }
}

看看这个,我已经解决了你的问题:codesandbox https://codesandbox.io/s/solitary-microservice-fcntj

使用 state.events 而不是 state.event 因为你已经将它注册为 reducer 中的事件而不是事件

 const mapStateToProps = state => ({
      event: state.events 
    });