React Redux如何在调度改变状态后向后端发出异步获取请求?

1sbrub3j  于 2023-08-05  发布在  React
关注(0)|答案(1)|浏览(90)

我有一个React Redux Toolkit切片,我想:
1.更新我的状态
1.将此更新状态获取到我的后端
我想做这样的事情:

const sendStateToBackend = createAsyncThunk(
    '.../sendStateToBackend',
    async (state) => {
        const data = await ...
    }
)

createSlice({
    ...,
    reducers: {
        addTodo:(state, action) => {
            state.todos.push(action.payload)
            dispatch(sendStateToBackend(state)) // This is an Anti pattern???
        }
    },
    extraReducers(builder) {
        builder.addCase(sendStateToBackend.pending, (state) => {
            state.isLoading = true
        }

        builder.addCase(sendStateToBackend.fulfilled, (state, action) => {
            state.isLoading = false
        }
    }
})

字符串
在我的页面.tsx:

const onSubmit = async (values) => {
    try {
        dispatch(addTodo(values))
        // Can I trigger another dispatch here? 
    } catch (error) {
        console.error('An error occurred while submitting the form: ', error)
    }
}


我该如何实现这一点?

lxkprmvk

lxkprmvk1#

您可以使用Redux Toolkit切片的extraReducers部分来处理由addTodo操作触发的API调用。不应该在addTodo reducer内部分派sendStateToBackend操作,而应该让extraReducersaddTodo操作完成时处理它。
以下是如何重构代码:
1-从切片中的addTodo reducer中删除分派:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

const sendStateToBackend = createAsyncThunk('.../sendStateToBackend', async (state) => {
  // Implement your API call here and return the response data
  // For example, you might use fetch or axios to send the state to the backend
  // const response = await fetch('your-api-url', {
  //   method: 'POST',
  //   body: JSON.stringify(state),
  //   headers: {
  //     'Content-Type': 'application/json',
  //   },
  // });
  // const data = await response.json();
  // return data;
});

const todoSlice = createSlice({
  name: 'todo',
  initialState: { todos: [], isLoading: false },
  reducers: {
    addTodo: (state, action) => {
      state.todos.push(action.payload);
    },
  },
  extraReducers(builder) {
    builder
      .addCase(sendStateToBackend.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(sendStateToBackend.fulfilled, (state, action) => {
        state.isLoading = false;
        // Do something with the response data from the backend if needed
        // const responseData = action.payload;
      });
  },
});

export const { addTodo } = todoSlice.actions;
export default todoSlice.reducer;

字符串
2-在你的page.tsx中,你可以在“onSubmit”函数中按顺序分派这两个动作:

import { useDispatch } from 'react-redux';
import { addTodo, sendStateToBackend } from './your-todo-slice';

const YourPageComponent = () => {
  const dispatch = useDispatch();

  const onSubmit = async (values) => {
    try {
      // Dispatch the addTodo action to update the state
      dispatch(addTodo(values));

      // Dispatch the sendStateToBackend action to send the updated state to the backend
      await dispatch(sendStateToBackend(values));
    } catch (error) {
      console.error('An error occurred while submitting the form: ', error);
    }
  };

  return (
    <div>
      {/* Your page content */}
    </div>
  );
};

export default YourPageComponent;


addTodo动作被调度时,它将更新Redux存储中的状态。然后,extraReducers部分将处理sendStateToBackend操作,当addTodo操作完成时,调用API将更新的状态发送到后端。通过在onSubmit函数中使用await,可以确保在继续执行其余代码之前完成API调用。

相关问题