从MongoDB加载数据到Redux Store fetching

w1jd8yoj  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(132)

在成功地设置了我的Node API和MongoDB之后,我目前的重点是将Redux集成到我的应用程序中。我将尝试在这里分享代码片段。
服务器顺序控制器按预期工作:

const getTotal = asyncHandler(async (req, res) => {

  const monthly = await Order.aggregate([
    {
      $group: {
        _id: { month: { $month: "$createdAt" }, year: { $year: "$createdAt" } },
        price: { $sum: "$price" },
      },
    },
  ]);

  res.status(200).json(monthly);
});

我想把数据输入到react redux中,但我遇到了一个问题。我在(store.js)中设置我的商店如下:

import { configureStore } from "@reduxjs/toolkit";
import { orderReducer } from "./orderSlice";
import { authReducer } from "./authSlice";


const store = configureStore({
    reducer: {
        auth: authReducer,
       order: orderReducer,
       
    }
});

export default store;

在这里命令切片

import { createSlice } from "@reduxjs/toolkit";

const orderSlice = createSlice({
   name: "order",
   initialState: {
    orders: [],
    order: null,
    total: [""],
   },
   reducers: {
      addOrder(state, action) {
         state.orders.push(action.payload);
      },  
      setOrders(state, action) {
         state.orders = action.payload;
       },
       setOrder(state,action) {
         state.order = action.payload;
       },
       setTotal(state,action) {
         state.total = action.payload;
       },
   }
});

const orderReducer = orderSlice.reducer;
const orderActions = orderSlice.actions;

export { orderActions, orderReducer }

和order API调用来获取total:

export function fetchTotal() {
    return async (dispatch) => {
      try {
        const { data } = await request.get(`/api/orders/total`);
        dispatch(orderActions.setTotal(data));
      } catch (error) {
        toast.error(error.response.data.message);
      }
    };
  }

所以现在我试图检索和显示数据表,但它不工作

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { fetchTotal } from './redux/orderApiCall';

export default function Total() {
  const dispatch = useDispatch();
  const { ordersTotal } = useSelector(state => state.order);

  useEffect(() => {
    dispatch(fetchTotal());
  }, []);
  return (
    <table className="table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Month</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      {ordersTotal?.map((item,index) => (
        <tr key={item._id}>
          <td>{index + 1}</td>
                  <td>{item?.price}</td>
        </tr>
      ))}
    </tbody>
  </table>

  )
}
bvjveswy

bvjveswy1#

fetchTotal是一个返回异步函数的函数,该函数接受dispatch作为参数,所以我假设dispatch(fetchTotal())不是正确的语法。试试这个

fetchTotal()(dispatch);

或者:

您可以使用createAsyncThunk()fetchTotal函数转换为Redux Thunk:

const fetchTotal = createAsyncThunk(
   'total/getTotla', //action type string
   // Callback function
   async (thunkAPI) => {
    const {data} = request.get(`/api/orders/total`)
   )
   return data
})

然后将reducer添加到切片以更新状态:

const orderSlice = createSlice({
name: "order",
initialState: {
orders: [],
order: null,
total: [""],
loading: false // Indicates if thunk data is ready
},
reducers: {
   // ...
}
extraReducers: {
   [getTotal.pending]: (state) => {
     state.loading = true
   },
   [getTotal.fulfilled]: (state, { payload }) => {
     state.loading = false
     state.total = payload
   },
   [getTotal.rejected]: (state) => {
     state.loading = false
   },
  },
});

这是@reduxjs/toolkit开发人员推荐的标准的Redux请求生命周期方法,它允许redux store完全控制异步请求以及它可能产生的任何结果或错误。

相关问题