Redux 工具包中的去抖动

问题描述 投票:0回答:1

我正在尝试使用 lodash 来消除以下 API 调用的反跳

debounce

export const getProfile = createAsyncThunk(
  GET_PROFILE,
  async (amount: any, { rejectWithValue }: any) => {
    try {
      const response = await API.Get(EndPoint.GET_PROFILE)
      console.log(response)
      return response.data
    } catch (error: any) {
      amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
      return rejectWithValue(error?.code || 'Something went wrong..!')
    }
  }
)

上面的函数运行没有任何错误,并且获取能够看到操作内部

fulfilled
的数据

所以我尝试按以下方式实现去抖

export const getProfile = createAsyncThunk(
  GET_PROFILE,
  debounce(async (amount: any, { rejectWithValue }: any) => {
    try {
      const response = await API.Get(EndPoint.GET_PROFILE)
      console.log(response)
      return response.data
    } catch (error: any) {
      amount.failCallBack(error?.response?.data?.msg || 'something_went_wrong')
      return rejectWithValue(error?.code || 'Something went wrong..!')
    }
  }, 5000)
)

现在网络应用程序中没有任何例外,当我

console.log
fulfilled
操作时,它会将
payload
显示为
undefined

{
    "type": "login/getProfile/fulfilled",
    "meta": {
        "arg": {
            "data": "login"
        },
        payload: undefined,
        "requestId": "8pfalpIzFl8nNOgi2jRcb",
        "requestStatus": "fulfilled"
    }
}

解决此问题的任何建议。

提前致谢

react-hooks react-redux redux-thunk redux-toolkit react-tsx
1个回答
2
投票

不要对有效负载创建者进行反跳 - 对调度 thunk 操作进行反跳。由于您可能不希望在组件中这样做,因此请通过手动 thunk 来完成它

const getProfile = createAsyncThunk( ... normal definition ... );
const debounced = debounce((arg, dispatch) => dispatch(getProfile(arg)), 5000);
const debouncedGetProfile = (arg) => (dispatch) => debounced(arg, dispatch)

然后使用它

dispatch(debouncedGetProfile(amount))
© www.soinside.com 2019 - 2024. All rights reserved.