如何在redux工具包切片中获得对dispatch()的引用



我有一个redux工具包切片文件,代码为

import { createSlice } from "@reduxjs/toolkit";
const slice = createSlice({
name: "users",   
initialState: [],
reducers: {
ADD: (state, {payload}) => { state.push(payload); },
DELETE: (state, {payload}) => { state = state.filter(u => u.id !== payload); }
}
});
export const { ADD, DELETE } = slice.actions;
export default slice.reducer;

我正在尝试设置一个firestoreonSnapshot侦听器,并在ADD、DELETE操作实时发生时调用它们。以下是我目前的做法:

...
...
...
export const { ADD, DELETE } = slice.actions;
export const listen = (dispatch /* passed in from component useDispatch() */) => {

const unsub = onSnapshot(collection(db, "users"), (snapshot)=>{
snapshot.docChanges().forEach(change => {

if(change.type === "added") {
dispatch(ADD( { ...doc.data(), id: doc.id }));
} else if (change.type === "removed") {
dispatch(DELETE(doc.id));
}
});
});
return unsub;
}

唯一的问题是,当我在useEffect中设置此函数时,我必须从某个组件传入dispatch

如何在不需要传入调度引用的情况下调用上面的函数?

PS:我已经知道createAsyncThunk有一个内置的调度引用,但onSnapshot不是异步调用的。它不适用于它。

我发现了如何使用返回函数的普通函数来实现这一点。如果函数返回函数,Redux将自动将引用传递给dispatch。

...
...
...
export const { ADD, DELETE } = slice.actions;
export const listen = () => dispatch => {

const unsub = onSnapshot(collection(db, "users"), (snapshot)=>{
snapshot.docChanges().forEach(change => {

if(change.type === "added") {
dispatch(ADD( { ...doc.data(), id: doc.id }));
} else if (change.type === "removed") {
dispatch(DELETE(doc.id));
}
});
});
return unsub;
}

相关内容

  • 没有找到相关文章

最新更新