【发布时间】:2021-01-25 17:22:38
【问题描述】:
我正在努力寻找如何最好地使用 redux thunk 调度多个操作的方法。首先,我想保持我所有的 thunk 隔离而不是混合它们,因为它当然会让我在任何地方使用它们(在一个视图中我可以发送 fetchData 然后显示一条消息说“数据已成功获取”,而在另一个视图中在获取数据后只是获取其他内容,或者在某些情况下,我想在我的 thunk 成功调度的情况下执行代码)。例如,假设我有下一个 thunk:
export const fetchData = () => async (dispatch, getState) => {
dispatch(fetchDataStart())
try {
const response = await fetch('https://jsonplaceholder.typicode.com/photos')
const data = await response.json()
dispatch(fetchDataSuccess(data))
// should i dispatch actions here and create more thunks like this one for differents
// situations
} catch (error) {
dispatch(fetchDataFailed(error))
throw error // is this throw error correct to stop the flow of the code
}
}
在我的组件中,我调度该操作来获取我需要的数据:
useEffect(() => {
// should i make this function async and await for the first dispatch and then dispatch
// another function
const loadUsers = () => {
dispatch(fetchData())
// await dispatch(fetchData())
// dispatch(nextAction())
}
loadUsers()
},[ ])
根据第一次提取分派另一个操作的正确方法是什么?
如果提取不成功,我是否应该在 thunk 中抛出错误以避免调度其他操作?
我应该分派组件中的下一个操作,还是只是根据我在一个操作后想要做什么来为每种不同的情况创建越来越多的 thunk? (这可能会使我的操作文件更大)
提前感谢您的帮助
【问题讨论】:
标签: reactjs redux redux-thunk