我在项目的其他区域使用了类似的 Thunk 和 slice,所有工作都按预期进行,但这个特定的不起作用,与此 Thunk 的区别在于它包含一个 axios 调用,该调用等待结果,以便它可以被链接到下一个 axios 调用。
登录后,我认为问题是 Thunk 在第一次 axios 调用后触发“fulfilled”,而不是等待完整的函数完成,这个问题让我很难解决这个问题。
export const getPlanAPI = createAsyncThunk('dataStorePlans/plan', async () => {
const response = await axios.get('/api/routes')
let promises = [];
const routeData = [];
// I think the Thunk is firing 'fulfilled' at this point.
try {
for (let i = 0; i < response.data.length; i++) {
promises.push(axios.get('/api/routedetail?planid=' + response.data[i].id + '&jobcount=' + response.data[i].jobs))
}
} catch (error) {
console.log(error);
}
Promise.all(promises).then(function (results) {
results.forEach(function (response) {
routeData.push(response.data[0]);
})
return routeData
});
});
export const planSlice = createSlice({
name: 'dataStorePlans/plan',
initialState: {
planList: [],
status: ''
},
reducers: {
getPlanState: (state) => {
return state
}
},
extraReducers: {
[getPlanAPI.pending]: (state, action) => {
state.status = 'Loading';
},
[getPlanAPI.fulfilled]: (state, action) => {
state.status = 'Success';
state.planList = action.payload
},
[getPlanAPI.rejected]: (state, action) => {
state.status = 'failed';
action.error = action.error.message;
}
}
});
最佳答案
主要问题是你的函数不会等待 Promise 完成。它也从未返回routeData
。
您还通过大量迭代和推拉东西使您的函数变得困惑。人们很容易忘记必须在哪里归还东西。我知道异步是新的热门内容,但 promise 链在这里效果更好。即使我保留你的结构,如果你在正确的地方使用 map
,函数也会变得更容易阅读。
export const getPlanAPI = createAsyncThunk('dataStorePlans/plan', async () => {
const response = await axios.get('/api/routes')
let promises = [];
try {
promises = response.data.map(({id, jobs}) =>
axios.get(`/api/routedetail?planid=${ id }&jobcount=${ jobs }`)
)
} catch (error) {
console.log(error);
}
return Promise
.all(promises)
.then(results =>
results.map(response => response.data[0])
)
});
关于reactjs - react redux,thunk 完成的事件过早发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65265525/