我使用typescript, useSelector和@reduxjs/toolkit…
…当我调度computeConfidenceIntervalsAsyncaction(参见下面的代码),我可以看到代码立即运行以下行:state.status = 'loading'
但是ViewComponent只有在payloadCreator完成运行doSomeHeavyComputation之后才会重新渲染。函数。
用另一种方式来解释它:在ViewComponent中,我希望在重计算之前呈现'loading'状态,但由于某种原因,重计算首先运行,然后我收到'loading'和'idle'在一行。
这个有什么帮助吗?
减速器:
//...
export const computeConfidenceIntervalsAsync = createAsyncThunk(
'forecast/getConfidenceIntervals',
async (data: ConfidenceIntervalsParams) => {
const response = await getConfidenceIntervals(data.totalRuns, data.itemsTarget, data.throughputs, new Date(data.startingDate));
return [...response.entries()];
}
);
export const forecastSlice = createSlice({
name: 'forecast',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(computeConfidenceIntervalsAsync.pending, (state) => {
state.status = 'loading';
})
.addCase(computeConfidenceIntervalsAsync.fulfilled, (state, action) => {
state.status = 'idle';
state.confidenceIntervals = action.payload;
});
}
});
export const selectForecast = (state: RootState) => state.forecast;
//...
服务:
//...
export function getConfidenceIntervals(totalRuns: number, itemsTarget: number, throughputs: number[], startingDate: Date) {
return new Promise<Map<string, number>>((resolve) => {
console.log('beginning');
const outcomes = doSomeHeavyComputation(totalRuns, itemsTarget, throughputs, startingDate);
console.log('ending');
resolve(outcomes);
});
}
//...
组件:
export function ViewComponent() {
const forecast = useAppSelector(selectForecast);
console.log(forecast)
if (forecast.status === 'loading') {
return (
<div>Loading...</div>
);
}
return (<div>...</div>);
useSelector钩
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../redux';
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
同步工作是阻塞的——这并不是cAT
设计的真正目的。您可以通过执行
export async function getConfidenceIntervals(totalRuns: number, itemsTarget: number, throughputs: number[], startingDate: Date) {
await Promise.resolve() // this will defer this to the next tick, allowing React to render in-between
console.log('beginning');
const outcomes = doSomeHeavyComputation(totalRuns, itemsTarget, throughputs, startingDate);
console.log('ending');
return outcomes;
}
(我冒昧地将其重写为async/await)
你的承诺将立即开始,没有暂停,所以我添加了一个await Promise.resolve()
,延迟执行一个tick。