如何解决此错误类型错误:无法在我的 redux 应用程序中读取 null 的属性(读取"indexOf")的属性



我正在做一个redux项目。下面是我的appSlice

export const appSlice = createSlice({
name: "app",
initialState: {
channelId: null,
channelName: null,
},
reducers: {
setChannelInfo: (state, action) => {
state.channelId = action.payload.channelId;
state.channelName = action.payload.channelName;
},
},
});

这是我的chat.jsx

const [message, setMessage] = useState([]);
//needed when you want to listen to a statechange in the database and fetch
useEffect(() => {
const messageRef = collection(db, "channels", channelId, "messages");
onSnapshot(messageRef, (snapshot) => {
setMessage(snapshot.docs.map((doc) => doc.data()));
});
}, [channelId]);

当我尝试运行浏览器时,它会给我这个错误

TypeError:无法读取null的属性(读取"indexOf"(

指向我的聊天.jsx,其中我有const messageRef=集合(…(

所以我怀疑在最初的呈现中,它读取了一个null值,从而破坏了我的代码。

我试过什么

当我将appSlice中的const channelId更改为具有值而不是null时,它就起作用了。

我只是不希望它有一个初始值,这就是它为null的原因,这样当用户现在点击id时,它就会填充它

所以我的问题是如何在不改变channelId的初始状态的情况下处理这个错误

我认为您需要加载以等待数据库调用完成并获得值。因此,我只需要将数据库调用移到它自己的钩子中,并返回三个data, isLoading, error。然后在你的chat.jsx中,你可以通过调用钩子来访问数据:

const [yourData, isLoading, error] = useYourCustomHook()

由于加载已经存在,您可以在数据库调用运行后返回加载指示符,然后在数据到达后更新useEffect中的状态。

相关内容

最新更新