Redux toolkit -调度后刷新存储



我在Redux上有一个问题,我希望你能帮助我。因此,我提取了一些存储变量,在我的页面中使用它们:

const {
selectedRows,
searchCriteria: { name, type},
cookies: { pageNumber, pageSize },
} = useSelector((store) => store.cookiesSearch);

在从表中选择了一些行之后,我按下一个按钮,另一个页面将有条件地呈现在包含cookie的表上,我将在那里执行一些操作,然后我想要刷新我的存储数据,用新数据再次填充表,在操作后修改。在按钮的onClick操作中,我有这样的内容:

onClick={() => {
dispatch(changeCookies());
// after this I want to refresh the cookies list from the table
// the next dispatch have to change pageNumber to 1, pageSize to 10 and the cookies list to []
dispatch(refreshCookiesList())
// the problem is that here the dispatch will use the old pageNumber and pageSize. for example if before the onClick action I was at page 3 in the table, the new rendered cookies list will be affected and the getCookiesList action will bring me the cookies from the third page 
dispatch(getCookiesList({ pageNumber, pageSize })) 
}}

我希望在changeCookies操作之后刷新表并从第1页开始。你有什么可能的解决办法吗?如何刷新存储数据?

默认情况下Redux是同步的,因此我们将中间件添加到存储中。这里有两种解决方案,即《思考》或《还原片》。我猜您正在使用redux-toolkit,其中包含现成的工具。在redux-toolkit中,您有createAsyncThunk功能,允许进行异步操作并调度它们。在这里,您可以访问getState,因此您不需要从外部(从组件)传递{ pageNumber, pageSize },但您可以直接从store获取它。

export const getCookiesList = createAsyncThunk('cookiesSearch/getCookiesList', (_, { getState }) => {
const const {
selectedRows,
searchCriteria: { name, type},
cookies: { pageNumber, pageSize },
} = getState().cookiesSearch 
// do stuff
})

坦克是作为同步函数调度的,所以你可以等待(如果你想要同步你的数据,你甚至必须等待):

onClick={async () => {
await dispatch(changeCookies());
cookies list to []
await dispatch(refreshCookiesList())
dispatch(getCookiesList({ pageNumber, pageSize })) 
}}

最新更新