gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'events' of undefined

转载 作者:行者123 更新时间:2023-12-01 16:16:51 25 4
gpt4 key购买 nike

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

事件.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
});

关于javascript - 类型错误 : Cannot read property 'events' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63148390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com