我是 React 的新手,目前我正在研究 React Redux 应用程序,我想删除 Redux 状态中数组内的项目。删除一项(移动)后,列表在 UseSelector 中显示为未定义
const mobileList = useSelector((state) => state.MobileReducer.mobileList);
并且由于列表未定义,因此该地图不起作用,但是在我收到错误后,我从 Redux 开发工具中检查了状态,它在列表中显示了没有删除项目的数组,并且此代码在添加项目时工作正常,状态更新和列表也显示最新。
列表组件
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import Table from "react-bootstrap/Table";
import Button from "react-bootstrap/Button";
import allActions from "../Actions/index";
import EditModal from "./EditModal";
const MobileList = () => {
const dispatch = useDispatch();
debugger;
const mobileList = useSelector((state) => state.MobileReducer.mobileList);
const [modalShow, setModalShow] = useState(false);
const editingItem = useSelector((state) => state.editingItem);
const [editItem, setEditItem] = useState(false);
useEffect(() => {
if(editItem){
setModalShow(true);
}else{
setModalShow(false);
}
}, [editItem]);
return (
<>
<h1>Available Mobiles</h1>
<Table responsive>
<thead>
<tr>
<th>Model Name</th>
<th>Brand Name</th>
<th>Year</th>
<th>Price</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{mobileList.map((item, i) => {
return [
<tr key={i}>
<td>{item.ModelName}</td>
<td>{item.Brand}</td>
<td>{item.Year}</td>
<td>{item.Price}</td>
<td>
<Button variant="info" onClick={() => setEditItem(item)}>
Edit
</Button>
</td>
<td>
<Button
variant="danger"
onClick={() =>
dispatch(allActions.MobileActions.deleteItem(item))
}
>
Delete
</Button>{" "}
</td>
</tr>,
];
})}
</tbody>
</Table>
{modalShow ? (
<EditModal
show={modalShow}
onHide={() => setModalShow(false)}
item={editItem}
onClean={() => setEditItem(null)}
/>
) : null}
</>
);
};
export default MobileList;
减速器
const initialMobileListState = {
mobileList:[],
editingItem:null
}
const counter = (state = initialMobileListState, action) => {
debugger;
switch(action.type){
case "SAVE":
return {
...state,
mobileList:[...state.mobileList, action.mobile]
}
case "EDIT":
return {
...state,
editingItem:[action.mobile]
}
case "DELETE":
return state.mobileList.filter(a=>a.Id !== action.mobile.Id)
default:
return state
}
}
export default counter
答案 0 :(得分:1)
你需要像这样修复Reducer。删除项目时,您需要将 state
保留在原始对象结构中,就像保存项目时一样。
const initialMobileListState = {
mobileList:[],
editingItem:null
}
const counter = (state = initialMobileListState, action) => {
debugger;
switch(action.type){
case "SAVE":
return {
...state,
mobileList:[...state.mobileList, action.mobile]
}
case "EDIT":
return {
...state,
editingItem:[action.mobile]
}
case "DELETE": // <--------------------------------
return {
...state,
mobileList: state.mobileList.filter(a=>a.Id !== action.mobile.Id)
}
default:
return state
}
}
export default counter