【发布时间】:2021-12-03 04:21:32
【问题描述】:
我正在使用 typescript、useSelector 和 @reduxjs/toolkit...
...当我调度 computeConfidenceIntervalsAsync 操作(参见下面的代码)时,我可以看到代码立即运行以下行:
state.status = 'loading'
但是ViewComponent只有在payloadCreator运行完doSomeHeavyComputation函数后才会重新渲染。
用另一种方式解释它:在 ViewComponent 中,我希望在繁重的计算之前呈现“加载”状态,但由于某种原因,首先运行繁重的计算,然后我连续收到“加载”和“空闲” .
对这个有帮助吗?
减速机:
//...
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>);
使用选择器挂钩
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;
【问题讨论】:
标签: reactjs react-redux react-hooks redux-thunk redux-toolkit