我一直在尝试使用Traversy Media的MERN堆栈教程通过遵循以下代码来学习MERN堆栈。我目前在Part 6上,正在尝试使用Redux删除项目;但是,当我单击该项目将其删除时,什么也没发生。
我一直在尝试使用Chrome上的Redux DevTools找出问题所在,当我尝试删除某项时,在“操作”标签下显示DELETE_ITEM,并且该操作的类型为:“ DELETE_ITEM”,并且有效负载为我单击的项目的ID,似乎都正确。
但是,当我去检查“ Diff”选项卡时,它只是说(状态是相等的),我认为这意味着一切正常,直到我到达itemReducers.js,因为状态没有显示
我已经检查并重新检查了代码是否有错字,但对我来说似乎都正确。也许我只是在丢失一些东西,因为我一直在弄乱代码,以试图找出问题出在哪里?
ShoppingList.js
import React, { Component } from 'react';
import { Container, ListGroup, ListGroupItem, Button } from 'reactstrap';
import { PropTypes } from "prop-types";
import uuid from 'uuid';
import { connect } from "react-redux";
import { getItems, deleteItem } from "../actions/itemActions";
const mapStateToProps = (state) => ({
item : state.item
});
class ShoppingList extends Component {
componentDidMount() {
this.props.getItems();
}
onDeleteClick = id => {
this.props.deleteItem(id);
};
render() {
const { items } = this.props.item;
return (
<Container>
<Button
style={{ margin: '2rem 0' }}
onClick={() => {
const name = prompt('Enter new item');
if (name) {
this.setState(state => ({
items : [...state.items, { id : uuid.v4(), name }]
}))
}
}}>
Add Item
</Button>
<ListGroup>
{items.map(({id, name}) => {
return (
<ListGroupItem key={ id }>
{ name }
<Button
style={{ float: 'right' }}
onClick={this.onDeleteClick.bind(this, id)}>×</Button>
</ListGroupItem>
)
})}
</ListGroup>
</Container>
);
}
}
ShoppingList.propTypes = {
getItems : PropTypes.func.isRequired,
item : PropTypes.object.isRequired
}
export default connect(mapStateToProps, { getItems, deleteItem })(ShoppingList);
itemActions.js
export const getItems = () => {
return {
type: "GET_ITEMS"
}
}
export const addItem = () => {
return {
type : "ADD_ITEM"
}
}
export const deleteItem = id => {
return {
type : "DELETE_ITEM",
playload: id
}
}
itemReducer.js
import uuid from 'uuid';
const initialState = {
items : [
{ id: uuid.v4(), name : 'steak'},
{ id: uuid.v4(), name : 'chicken'},
{ id: uuid.v4(), name : 'eggs'}
]
}
const itemReducer = (state = initialState, action) => {
switch (action.type) {
case "GET_ITEMS" :
return {...state};
case "ADD_ITEM" :
state = {};
break;
case "DELETE_ITEM" :
return {
...state,
items : state.items.filter(item => item.id !== action.payload)
};
default :
return {...state};
}
}
export default itemReducer;
store.js
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import itemReducer from './reducers/itemReducer';
const initialState = {};
const middleware = [thunk];
let store = createStore(combineReducers({item : itemReducer}), initialState, compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));
export default store;