我正在跟随Traversy Media的MERN堆栈课程,在redux部分。我收到有关reducers初始化的错误,虽然我已经多次检查我的代码与教师的代码,但找不到差异。
我尝试更改各种导入和导出语句,有时会给出无关的错误,当我将其更改回来时会消失。
这是我的itemReducer.js
import uuid from "uuid";
import { GET_ITEMS, ADD_ITEM, DELETE_ITEM } from "../actions/types";
const initialState = {
items: [
{ id: uuid(), name: "Eggs" },
{ id: uuid(), name: "Milk" },
{ id: uuid(), name: "Steak" },
{ id: uuid(), name: "Candy" }
]
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_ITEMS:
return {
...state
};
}
}
index.js
import { combineReducers } from "redux";
import itemReducer from "./itemReducer";
export default combineReducers({
item: itemReducer
});
和ShoppingList.js
import React, { Component } from "react";
import { Container, ListGroup, ListGroupItem, Button } from "reactstrap";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import uuid from "uuid";
import { connect } from "react-redux";
import { getItems } from "../actions/itemActions";
import PropTypes from "prop-types";
class ShoppingList extends Component {
componentDidMount() {
this.props.getIems();
}
render() {
const { items } = this.props.item;
return (
<Container>
<Button
color="dark"
style={{ marginBottom: "2rem" }}
onClick={() => {
const name = prompt("Enter Item");
if (name) {
this.setState(state => ({
items: [...state.items, { id: uuid, name }]
}));
}
}}
>
Add Item
</Button>
<ListGroup>
<TransitionGroup className="shopping-list">
{items.map(({ id, name }) => (
<CSSTransition key={id} timeout={500} classNames="fade">
<ListGroupItem>
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={() => {
this.setState(state => ({
items: state.items.filter(item => item.id !== id)
}));
}}
>
×
</Button>
{name}
</ListGroupItem>
</CSSTransition>
))}
</TransitionGroup>
</ListGroup>
</Container>
);
}
}
ShoppingList.propTypes = {
getItems: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
item: state.item
});
export default connect(
mapStateToProps,
{ getItems }
)(ShoppingList);
预期结果:我希望http://localhost:3000加载购物清单,其中包含可以删除或添加的商品。
实际结果:我得到的是这个错误Error: Reducer "item" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
原因在于,当创建商店时,会调度INIT
动作,以便每个reducer返回其初始状态source,在您的情况下,您的reducer不知道如何处理INIT
动作(它返回undefined,那是为什么你得到错误)
你可以通过向你的reducer添加一个default
案例来解决这个问题:
export default function(state = initialState, action) {
switch (action.type) {
case GET_ITEMS:
return {
...state
};
default:
return state
}
}