从MongoDB加载数据到Redux Store fetching

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

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

  1. const getTotal = asyncHandler(async (req, res) => {
  2. const monthly = await Order.aggregate([
  3. {
  4. $group: {
  5. _id: { month: { $month: "$createdAt" }, year: { $year: "$createdAt" } },
  6. price: { $sum: "$price" },
  7. },
  8. },
  9. ]);
  10. res.status(200).json(monthly);
  11. });

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

  1. import { configureStore } from "@reduxjs/toolkit";
  2. import { orderReducer } from "./orderSlice";
  3. import { authReducer } from "./authSlice";
  4. const store = configureStore({
  5. reducer: {
  6. auth: authReducer,
  7. order: orderReducer,
  8. }
  9. });
  10. export default store;

在这里命令切片

  1. import { createSlice } from "@reduxjs/toolkit";
  2. const orderSlice = createSlice({
  3. name: "order",
  4. initialState: {
  5. orders: [],
  6. order: null,
  7. total: [""],
  8. },
  9. reducers: {
  10. addOrder(state, action) {
  11. state.orders.push(action.payload);
  12. },
  13. setOrders(state, action) {
  14. state.orders = action.payload;
  15. },
  16. setOrder(state,action) {
  17. state.order = action.payload;
  18. },
  19. setTotal(state,action) {
  20. state.total = action.payload;
  21. },
  22. }
  23. });
  24. const orderReducer = orderSlice.reducer;
  25. const orderActions = orderSlice.actions;
  26. export { orderActions, orderReducer }

和order API调用来获取total:

  1. export function fetchTotal() {
  2. return async (dispatch) => {
  3. try {
  4. const { data } = await request.get(`/api/orders/total`);
  5. dispatch(orderActions.setTotal(data));
  6. } catch (error) {
  7. toast.error(error.response.data.message);
  8. }
  9. };
  10. }

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

  1. import React, { useEffect } from 'react'
  2. import { useDispatch, useSelector } from 'react-redux';
  3. import { fetchTotal } from './redux/orderApiCall';
  4. export default function Total() {
  5. const dispatch = useDispatch();
  6. const { ordersTotal } = useSelector(state => state.order);
  7. useEffect(() => {
  8. dispatch(fetchTotal());
  9. }, []);
  10. return (
  11. <table className="table">
  12. <thead>
  13. <tr>
  14. <th>Id</th>
  15. <th>Month</th>
  16. <th>Price</th>
  17. </tr>
  18. </thead>
  19. <tbody>
  20. {ordersTotal?.map((item,index) => (
  21. <tr key={item._id}>
  22. <td>{index + 1}</td>
  23. <td>{item?.price}</td>
  24. </tr>
  25. ))}
  26. </tbody>
  27. </table>
  28. )
  29. }
bvjveswy

bvjveswy1#

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

  1. fetchTotal()(dispatch);

或者:

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

  1. const fetchTotal = createAsyncThunk(
  2. 'total/getTotla', //action type string
  3. // Callback function
  4. async (thunkAPI) => {
  5. const {data} = request.get(`/api/orders/total`)
  6. )
  7. return data
  8. })

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

  1. const orderSlice = createSlice({
  2. name: "order",
  3. initialState: {
  4. orders: [],
  5. order: null,
  6. total: [""],
  7. loading: false // Indicates if thunk data is ready
  8. },
  9. reducers: {
  10. // ...
  11. }
  12. extraReducers: {
  13. [getTotal.pending]: (state) => {
  14. state.loading = true
  15. },
  16. [getTotal.fulfilled]: (state, { payload }) => {
  17. state.loading = false
  18. state.total = payload
  19. },
  20. [getTotal.rejected]: (state) => {
  21. state.loading = false
  22. },
  23. },
  24. });

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

展开查看全部

相关问题