在redux部分,我将遵循Traversy Media的MERN堆栈课程。尽管我已多次将代码与讲师的代码进行核对并且找不到任何区别,但是我在简化器的初始化方面遇到了错误。
我尝试更改各种导入和导出语句,有时会给出不相关的错误,这些错误会在我将其更改回时消失。
这是我的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.
答案 0 :(得分:0)
之所以这样,是因为在创建商店时会调度INIT
动作,以便每个减速器返回其初始状态source,而在您的情况下,减速器不知道如何处理INIT
操作(返回未定义,这就是您收到错误的原因)
您可以通过在减速机中添加default
箱来解决此问题:
export default function(state = initialState, action) {
switch (action.type) {
case GET_ITEMS:
return {
...state
};
default:
return state
}
}