我尝试呈现firestore数据库中的项目。它在第一次渲染时正确显示,但当我在选项卡/导航之间切换时,它会再次将数据读取到列表中。如果我一直在标签间切换,它会添加越来越多的标签。
当我使用本地状态没有问题,但问题是,当我使用调度来显示项目,它会读取更多的项目到列表(而不是firestore数据库)。
useEffect(
() =>
onSnapshot(collection(db, "users"), (snapshot) => {
console.log(
"snapshot",
snapshot.docs.map((doc) => doc.data())
);
const firebaseData = snapshot.docs.map((doc) => doc.data());
dispatch(addItem(firebaseData));
setLocalState(firebaseData);
}),
[]
);
itemsSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
items: [],
};
const itemsSlice = createSlice({
name: "addItems",
initialState,
reducers: {
addItem: (state, action) => {
state.items.push(...action.payload);
},
emptyItems: (state) => {
state.items = [];
},
},
});
export const { addItem, emptyItems } = itemsSlice.actions;
export default itemsSlice.reducer;
下面是这个问题的gif:https://gyazo.com/bf033f2362d9d38e9eb315845971e224
因为我不明白您是如何在选项卡之间切换的,所以我无法告诉您为什么组件似乎正在重新呈现。useEffect
钩子负责像componentDidMount
和componentDidUpdate
方法一样工作。并且全局redux状态不会在每次渲染后重置自己(这就是为什么它如此伟大)。这不是组件状态的情况,每次从dom中移除并添加组件时,都会重置组件状态。这解释了为什么当您使用本地状态时,问题就消失了。这并不是说它是固定的,而是因为每次删除和添加组件时状态都会重置(这似乎就是这里发生的事情)。因为我们没有完整的细节,一个快速的修复应该是替换这个
state.items.push(...action.payload);
与
state.items = [...action.payload];
这将设置一个新值为state.items
,而不是将其压入。