6.基础教程-性能与数据范式化

本文最后更新于:2023年12月5日 晚上

export const fetchNotifications = createAsyncThunk("notifications/fetchNotifications", async (_, { getState }) => {
 const allNotifications = selectAllNotifications(getState())
 const [latestNotification] = allNotifications
 const latestTimestamp = latestNotification ? latestNotification.date : ""
 const response = await client.get(`/fakeApi/notifications?since=${latestTimestamp}`)
 return response.data
})

Thunk 参数

payload creator 的第二个参数是一个’ thunkAPI ‘对象,包含几个有用的函数和信息:

  • dispatchgetStatedispatchgetState 方法由 Redux store 提供。你可以在 thunk 中使用这些来发起 action,或者从最新的 Redux store 中获取 state (例如在发起 另一个 action 后获取更新后的值)。
  • extra:当创建 store 时,用于传递给 thunk 中间件的“额外参数”。这通常时某种 API 的包装器,比如一组知道如何对应用程序的服务器进行 API 调用并返回数据的函数,这样你的 thunk 就不必直接包含所有的 URL 和查询逻辑。
  • requestId:该 thunk 调用的唯一随机 ID ,用于跟踪单个请求的状态。
  • signal:一个AbortController.signal 函数,可用于取消正在进行的请求。
  • rejectWithValue:一个用于当 thunk 收到一个错误时帮助自定义 rejected action 内容的工具。

(如果你要手写 thunk 而不是使用 createAsyncThunk,则 thunk 函数将获取 (dispatch, getState) 作为单独的参数,而不是将他们放在一个对象中。)


6.基础教程-性能与数据范式化
http://blog.lujinkai.cn/前端/React/redux/6.基础教程-性能与数据范式化/
作者
像方便面一样的男子
发布于
2023年5月29日
更新于
2023年12月5日
许可协议