在我在网上看到的所有示例以及 RTK 本身的文档中,我看到人们在相同的范围内中止它,
import { fetchUserById } from './slice'
import { useAppDispatch } from './store'
import React from 'react'
function MyComponent(props) {
const dispatch = useAppDispatch()
React.useEffect(() => {
// Dispatching the thunk returns a promise
const promise = dispatch(fetchUserById(props.userId))
return () => {
// `createAsyncThunk` attaches an `abort()` method to the promise
promise.abort()
}
}, [props.userId])
}
如果我想在不同范围内中止承诺怎么办:
使用案例: 搜索按钮从缓慢的 api 获取数据,我用
启动搜索dispatch(placesFetchData({
lattitude: location.coords.latitude,
longitude: location.coords.longitude,
}));
用户单击另一个“选项卡”(即导航到另一个组件)
我们运行promise.abort() 两者都在 useEffect 中,返回作用域(即组件卸载)
或者用户点击“取消搜索”
我应该将承诺存储在 useState 中,以便我可以在整个组件中访问它吗?这样做感觉有点笨拙,你们有什么建议
我用 useRef() 解决了它
const abortSearch = useRef();
abortSearch.current=dispatchPromise.abort;
我可以在我的组件中的任何地方使用它来取消承诺
abortSearch.current("取消原因");
我使用的控制器可以在我的应用程序中作为单例进行访问。我在这里分派由组件触发的操作。
我在控制器类中有一个私有属性。
private abort: ((reason: string | undefined) => void) | undefined;
当我发送动作时,我就会运行
this.setAbort(action.abort);
其中 setAbort() 是一个基本的 setter
然后当我需要中止时,我会:
if (this.abort) this.abort("Aborting");