React-Redux中Reducer未向Store传递值:用户删除功能实现故障问询
Let's break down the issues in your code and fix them step by step:
Key Problems in Your Current Implementation
- Missing export for action type: The
DELETED_USERconstant intype.jsisn't exported, so your action and reducer can't reference it properly (this would throw an "undefined" error). - Incorrect payload property access: In your reducer, you're trying to access
action.payload.content, but your action defines the filtered data underaction.payload.employees. - Wrong state update logic: You're attempting to delete a user, but your reducer is appending a new object to the
finalUserarray instead of replacing it with the filtered list. This would result in a nested, incorrect state structure.
Fixed Code Files
1. type.js
First, export the action type so other files can use it:
export const DELETED_USER = "DELETED_USER";
2. action.js
Import the action type, keep the filtering logic, and ensure consistent naming:
import { DELETED_USER } from './type'; export const deletedUser = (userId, employees) => { return { type: DELETED_USER, payload: { // Return filtered array, or empty array if employees is undefined employees: employees ? employees.filter(employee => employee.id !== userId) : [] } }; };
3. Reducer.js
Import the action type, fix the state update to replace the user list, and use standard Redux naming conventions:
import { DELETED_USER } from './type'; // Use "initialState" instead of "finalState" (common Redux convention) const initialState = { finalUser: [] }; const reducer = (state = initialState, action) => { switch (action.type) { case DELETED_USER: // Replace finalUser with the filtered employees array from the action payload return { ...state, finalUser: action.payload.employees }; default: return state; } }; export default reducer;
4. store.js
Ensure the reducer import path is correct (adjust if your directory structure differs):
import { createStore } from "redux"; import reducer from './todo/reducer'; export default createStore(reducer);
Quick Usage Note in Your Component
When triggering the delete action from a component, make sure to pass the current list of employees and the target user ID. For example, using React-Redux hooks:
import { useDispatch, useSelector } from 'react-redux'; import { deletedUser } from './action'; function EmployeeList() { const dispatch = useDispatch(); const employees = useSelector(state => state.finalUser); const handleDelete = (userId) => { dispatch(deletedUser(userId, employees)); }; // Render your employee list with delete buttons that call handleDelete }
内容的提问来源于stack exchange,提问作者Esmail
相关产品推荐
相关产品推荐

