【问题标题】:Ho do I mutate state on asyncThunk pending status in Redux-Toolkit?如何在 Redux-Toolkit 中改变异步 Thunk 挂起状态的状态?
【发布时间】:2020-12-15 05:12:42
【问题描述】:

有一个 asyncThunk putCurrency。所以我想计算它的等待时间。这是我尝试实现它的方式......(它在我的 react-app 顺便说一句)

const dataSlice = createSlice({
  name: 'data',
  initialState: { currency: { pendingTime: 0 } },
  extraReducers: {
    [putCurrency.pending]: state => {
      setInterval(() => {
        state.currency.pendingTime++
      }, 1000)
    }
  }
})

但它给了我一个 TypeError: Cannot perform 'get' on a proxy that has been revoke。我希望你明白了,那么有没有其他方法可以改变 pedning 状态的状态???谢谢

【问题讨论】:

    标签: reactjs redux-toolkit


    【解决方案1】:

    我创建了一个单独的组件,用于分派动作以更改状态。 不是真正的解决方案,但它解决了问题

    【讨论】:

      【解决方案2】:

      thunk 调度了三个动作。您可以拥有单独的减速器,或将其添加到现有的减速器中。在pending 上,您将捕获开始时间,在fulfilledrejected 上将计算新时间。它看起来像这样:

      function start(state) {
        state.start = Date.now();
      }
      
      function calculate(state) {
        state.lastTimeToComplete = Date.now() - start;
      }
      
      let thunkPerformance = createSlice({
        intialState: {
          start: 0,
          lastTimeToComplete: 0
        },
        reducers: {},
        extraReducers: {
          [thunk.pending]: start,
          [thunk.fulfilled]: calculate,
          [thunk.rejected]: calculate
        }
      })
      

      此解决方案不包括 thunk 将被多次执行的情况。第二个将重写start,第一个完成将计算lastTimeToComplete。但作为开始,它会起作用。

      另一种解决方案是在 thunk 和调度操作中开始间隔,并在结束时清除此间隔。

      【讨论】:

        猜你喜欢
        • 2021-11-21
        • 2016-09-22
        • 2017-10-23
        • 2022-01-05
        • 1970-01-01
        • 2020-12-14
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        相关资源
        最近更新 更多