【问题标题】:Is it necessary to save everything in redux state?是否有必要将所有内容都保存在 redux 状态?
【发布时间】:2021-04-29 00:00:56
【问题描述】:

我正在使用 redux-toolkit。一切正常,但现在我面临架构问题。

我需要调用一个端点来获取一些数据,以便进行最终调用。

我将使用这个最终的调用响应来创建和执行一些逻辑,以便在商店中调度和保存,所以:

1- 我是否应该在同一个 createAsyncThunk 调用中同时执行这两个调用并返回我需要的内容?

2- 这个 asyncthunk 调用只会处理数据,我真的不需要它来保存任何东西,基于这 2 个调用,它会调度其他操作。我应该把它放在哪里?

【问题讨论】:

    标签: reactjs redux redux-toolkit


    【解决方案1】:

    我有调度其他异步 thunk 的异步 thunk,没问题。

    1- 是的,尽管可能更难跟踪哪个 api 失败

    2- 在我看来,如果这个 thunk 和其他人一起生活会更容易

    例子:

    const BASE = 'user';
    
    // some other thunk in another file, ignore implementation
    const saveInLocalStorageAC = createAsyncThunk()
    
    const fetchUserAC = createAsyncThunk(`${BASE}/fetch`, async (email, { dispatch }) => {
      const id = await getIdFromEmail(email); // service
      await dispatch(saveInLocalStorageAC({ loggedInUser: { id, email } })); // thunk
      return id;
    })
    
    const slice = createSlice({
      name: BASE,
      initialState: someInitialState,
      reducers: {},
      extraReducers: builder => {
        builder.addCase(fetchUserAC.fulfilled, (state, action) => {
          // here is where I decide if I want to update the state or not
          state.data = action.payload // id
        })
      },
    })
    
    export default slice.reducer;
    

    如果您使用某种记录器检查操作,您会看到如下内容:

    user/fetch/pending
    storage/save/pending
    storage/save/fulfilled
    user/fetch/fulfilled
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2020-01-05
      • 2021-08-06
      相关资源
      最近更新 更多