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

使用Redux Toolkit从MERN栈后端API获取用户数据失败求助

问题描述

我正在用Redux Toolkit开发MERN栈电商商城,登录功能已实现且运行正常,但获取所有用户/客户数据并更新Redux Store的功能无法实现。后端API经Postman测试运行正常,我是Redux Toolkit新手,请审查以下代码并指出错误:


Customer Slice代码:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import customerService from "./customerService";

export const getUsers = createAsyncThunk(
  "customer/get-customers",
  async (thunkAPI) => {
    try {
      return await customerService.getUsers();
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);
const initialState = {
  customer: [],
  isError: false,
  isLoading: false,
  isSuccess: false,
  message: "",
};
export const customerSlice = createSlice({
  name: "users",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getUsers.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getUsers.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isError = false;
        state.isSuccess = true;
        state.customer = action.payload;
      })
      .addCase(getUsers.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.isSuccess = false;
        state.message = action.error;
      });
  },
});
export default customerSlice.reducer;

Customer Service代码:

import axios from "axios";
import { base_url } from "../../utils/base_url"

const getUsers = async () => {
  const response = await axios.get(`${base_url}user/allusers`);
  console.log(response.data);
  return response.data;
};

const customerService = {
  getUsers,
};

export default customerService;

Redux Store代码:

import { configureStore } from "@reduxjs/toolkit";
import authReducer from '../features/auth/authSlice'
import customerReducer from '../features/customer/customerSlice'


export const store=configureStore({
    reducer:{auth:authReducer,customers:customerReducer}
})

Customer页面代码:

import React from 'react'
import {useDispatch,useSelector} from 'react-redux'
import { Table } from 'antd';
import { useEffect } from 'react'
import { getUsers } from '../features/customer/customerSlice';

const columns = [
  {
    title: 'No.',
    dataIndex: 'key',
  },
  {
    title: 'Name',
    dataIndex: 'name',
  },
  {
    title: 'Product',
    dataIndex: 'product',
  },
  {
    title: 'Status',
    dataIndex: 'status',
  },
];
const data1 = [];
for (let i = 0; i < 46; i++) {
  data1.push({
    key: i,
    name: `Hanzla Zahid ${i}`,
    product: `Laptop ${i}`,
    status: `Pending ${i}`,
  })
}

const Customer = () => {
  const dispatch=useDispatch()
  useEffect(()=>{
    dispatch(getUsers())
  },[])
  return (
    <div>
    <h3 className='mb-4 title'>Customers</h3>
    <div><Table columns={columns} dataSource={data1} /></div>
</div>
  )
}

export default Customer

后端API代码:

GetAllUsers=asyncHandler(async(req,res)=>{
    try{
        const data=await User.find()
        res.json(data)
    }catch(err){
        console.log(err)
        console.log("Users Data Not Fetched")
    }
})

错误分析与修复方案
  1. createAsyncThunk参数格式错误
    createAsyncThunk的第二个参数应为async (arg, thunkAPI) => {},你错误地将thunkAPI作为第一个参数传入。修改如下:
export const getUsers = createAsyncThunk(
  "customer/get-customers",
  async (_, thunkAPI) => { // 用_占位不需要的参数
    try {
      return await customerService.getUsers();
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response?.data || error.message); // 优先取后端返回的错误信息
    }
  }
);
  1. 页面未从Redux Store读取真实数据
    当前页面一直使用模拟的data1,未从Redux中获取接口返回的用户数据。修改页面代码:
const Customer = () => {
  const dispatch=useDispatch()
  // 从store的customers节点读取数据
  const { customer, isLoading } = useSelector((state) => state.customers);

  useEffect(()=>{
    dispatch(getUsers())
  },[])

  // 将后端返回的用户数据转换为AntD Table需要的格式
  const tableData = customer.map((user, index) => ({
    key: index,
    name: user.name, // 匹配后端User模型的字段
    product: 'N/A', // 若用户数据无product字段,根据实际业务调整
    status: user.isActive ? 'Active' : 'Inactive' // 匹配后端用户状态字段
  }));

  return (
    <div>
      <h3 className='mb-4 title'>Customers</h3>
      <div>
        <Table 
          columns={columns} 
          dataSource={tableData} 
          loading={isLoading} // 加载状态联动
        />
      </div>
    </div>
  )
}
  1. rejected状态错误信息赋值错误
    在getUsers.rejected分支中,通过thunkAPI.rejectWithValue传递的错误应从action.payload获取,而非action.error:
.addCase(getUsers.rejected, (state, action) => {
  state.isLoading = false;
  state.isError = true;
  state.isSuccess = false;
  state.message = action.payload || action.error.message;
});
  1. Axios请求可能缺少认证信息
    若后端接口需要登录认证(如JWT),需在请求头中携带token:
const getUsers = async () => {
  const token = localStorage.getItem('token'); // 假设登录后token存在localStorage
  const response = await axios.get(`${base_url}user/allusers`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
  return response.data;
};

内容的提问来源于stack exchange,提问作者Hanzla Zahid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:22:53