如何在 redux 工具包切片中获取对 dispatch() 的引用?
How can I get a reference to dispatch() in a redux toolkit slice?
我有一个包含以下代码的 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;
我正在尝试设置一个 firestore onSnapshot
侦听器并在实时发生时调用 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
内置了dispatch的引用,但是onSnapshot
并没有被异步调用。不适用于它。
我发现了如何使用一个 returns 函数的普通函数来完成它。如果函数 returns a function.
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;
}
我有一个包含以下代码的 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;
我正在尝试设置一个 firestore onSnapshot
侦听器并在实时发生时调用 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
内置了dispatch的引用,但是onSnapshot
并没有被异步调用。不适用于它。
我发现了如何使用一个 returns 函数的普通函数来完成它。如果函数 returns a function.
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;
}