You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Missing export for action type: The DELETED_USER constant in type.js isn't exported, so your action and reducer can't reference it properly (this would throw an "undefined" error).
  2. Incorrect payload property access: In your reducer, you're trying to access action.payload.content, but your action defines the filtered data under action.payload.employees.
  3. Wrong state update logic: You're attempting to delete a user, but your reducer is appending a new object to the finalUser array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:47:27