我正在学习一个尝试学习 Redux 的教程。我得到了第一个动作,这是一个简单的 GET API 调用,但我被困在我试图创建的下一个动作上。代码如下所示:在组件中:class ShoppingList extends Component { componentDidMount() { this.props.getItems(); } handleClick = id => { console.log("component " + id); this.props.deleteItem(id); }; render() { const { items } = this.props.item; return ( <Container> <ListGroup> <TransitionGroup className="shoppingList"> {items.map(({ id, name }) => ( <CSSTransition key={id} timeout={500} classNames="fade"> <ListGroupItem> <Button className="button1" color="danger" size="sm" onClick={e => this.handleClick(id, e)} > × </Button> {name} </ListGroupItem> </CSSTransition> ))} </TransitionGroup> </ListGroup> </Container> ); }}ShoppingList.propTypes = { getItems: PropTypes.func.isRequired, item: PropTypes.object.isRequired, deleteItem: PropTypes.func.isRequired};const mapStateToProps = state => ({ item: state.item});export default connect(mapStateToProps, { getItems, deleteItem })(ShoppingList);在我的减速机中:const initialState = { items: [ { id: 3, name: "Eggs" }, { id: 4, name: "Milk" }, { id: 5, name: "Steak" }, { id: 6, name: "Water" } ]};export default function(state = initialState, action) { switch (action.type) { case GET_ITEMS: return { ...state }; case DELETE_ITEM: console.log("reducer"); return { ...state, items: state.items.filter(item => item.id !== action.id) }; default: return state; }}但是,当我单击按钮尝试从列表中删除项目时,没有任何反应。我可以在 Redux 控制台中看到正在调度该操作,但它似乎没有任何效果。有什么建议么?
1 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
你有在deleteItem行动{ type, payload }。相反,您可以在 reducer return 语句中拥有{ type, id }或使用。payload
我会做以下事情 - 所以你通过id而action不是传递payload:
export const deleteItem = id => {
console.log("actions");
return {
type: DELETE_ITEM,
id
};
};
或者以后用途的最佳选择 - 继续payload添加id为属性:
// action
export const deleteItem = id => {
console.log("actions");
return {
type: DELETE_ITEM,
payload: { id }
};
};
// reducer
case DELETE_ITEM:
// here destructuring the property from payload
const { id } = action.payload;
return {
...state,
items: state.items.filter(item => item.id !== id)
};
我希望这有帮助!
添加回答
举报
0/150
提交
取消