【发布时间】:2022-08-19 06:56:15
【问题描述】:
我看到了这个https://redux-toolkit.js.org/api/createAsyncThunk#canceling-while-running
但我在onClick 处理程序中有两个调度函数。
如何将它们放入useEffect()?
我想实现当用户快速点击另一个项目时,之前的fetchFileContentsHandler 将被取消,并始终返回最新调用的结果。
我试图将fetchFileContentsHandler 包裹在useCallback() 中,
并将fetchFileContentsHandler 放入useEffect() 并进行清理返回。
但它导致了奇怪的行为。
const fetchFileContentsHandler = () => {
dispatch(fetchFileContents(props.params));
dispatch(
changeSelectedFile({ selectedFile: props.params, selected: true })
);
};
return (
<NavLink to=\"#\" key={fileName}>
<ListItemButton
selected={props.selected}
onClick={fetchFileContentsHandler}
>
<ListItemText
primary={fileName}
/>
</ListItemButton>
</NavLink>
);
};
export default Items;
[更新]
我尝试将fetchFileContents 更改为createAsyncThunk 并添加建议的useRef() 和.abort(),但没有成功。
如果第一个 fetchFileContents 花费的时间比第二个 fetchFileContents 长,它仍然会更新 htmlReport 或 textReport 值,我会使用这个值并在另一个组件中显示内容。
切片.js
export const fetchFileContents = createAsyncThunk(
\"ui/getFileContents\",
async (fileName) => {
const fileContentsResponse = await fetch(...);
const response = await fileContentsResponse.json();
return {
fileType: fileName.includes(\"html\") ? \"text\" : \"html\",
contents: data,
};
}
);
const Slice = createSlice({
name: \"somename\",
initialState: {
htmlReport: null,
textReport: null,
},
reducers: {
},
extraReducers: (builder) => {
builder
.addCase(fetchFileContents.fulfilled, (state, action) => {
if (action.payload.fileType === \"textg\") {
state.textReport = action.payload.contents;
state.htmlReport = null;
} else if (action.payload.fileType === \"html\") {
state.textReport = null;
state.htmlReport = action.payload.contents;
}
})
},
});
组件.js
const fetchFileContentsPromise = useRef();
const fetchFileContentsHandler = () => {
fetchFileContentsPromise.current?.abort();
fetchFileContentsPromise.current = dispatch(
fetchFileContents({ fileName: props.params })
);
dispatch(
changeSelectedFile({ selectedFile: props.params, selected: true })
);
};
标签: reactjs redux-toolkit