如何将 useReducer React js 与 firestore 一起使用?它总是返回“未定义”。
我正在尝试将reducer与firebase一起使用,但是如果我在
useEffect
中使用dispatch,我将无法获取数组。
userType
工作正常。我做错了什么?
首次渲染
app.js
页面时,我想加载登录的用户数据,用户数据
以及firestore中的订单信息产品信息,放入状态,进行管理。
如果有更好的方法,请推荐。
const iState = {
orders: [],
userType: "before",
};
function reducer(state, action) {
switch (action.type) {
case "ORDERS":
return { orders: [...state.orders, [action.order]] };
case "CHANGE":
return { userType: action.userType };
default:
return state;
}
}
function Counter() {
const [user, loading] = useAuthState(auth);
const [state, dispatch] = useReducer(reducer, iState);
const { orders, userType } = state;
useEffect(() => {
db.collection("accounts")
.doc(user?.email)
.get()
.then(doc => dispatch({ type: "CHANGE", userType: doc?.data()?.type }));
db.collection("orders")
.doc("b2b")
.collection("b2borders")
.onSnapshot(snapshot =>
dispatch({
type: "ORDERS",
order: snapshot.docs.map(doc => ({ id: doc.id, data: doc.data() })),
})
);
}, [user, dispatch]);
if (loading || userType === "before") {
return (
<div className="grid place-items-center h-screen w-full">
<div className="text-center pb-24 flex flex-col justify-center items-center">
<Spinner name="ball-spin-fade-loader" color="gray" fadeIn="none" />
</div>
</div>
);
}
if (user && userType === "admin") {
return (
<div className="grid place-items-center h-screen w-full">
{console.log(orders)}
</div>
);
}
return (
<>
<div className="grid place-items-center h-screen w-full">
<div className="text-center pb-24 flex flex-col justify-center items-center">
<Spinner name="ball-spin-fade-loader" color="gray" fadeIn="none" />
</div>
</div>
</>
);
}
export default Counter;
您没有正确编写您的减速器。减速器是一个纯函数,它将当前状态和调度的操作作为输入并返回新状态。因此,每当您从减速器返回新状态对象时,它都会完全替换当前状态对象,而不是将新状态与当前状态合并。
所以,你必须将你的减速器更改为这样的:
function reducer(state, action) {
switch (action.type) {
case "ORDERS":
return {...state, orders: [...state.orders, {...action.order}] };
case "CHANGE":
return {...state, userType: action.userType };
default:
return state;
}
}