不能在 useEffect() 中使用 dispatch 和 redux

Can't use dispatch inside useEffect() with redux

我不能在 useEffect 中使用 dispatch 一旦我添加该行,它就会向我显示此错误

import { useDispatch } from 'react-redux'
import db from '../firebase'
import setProjects from '../features/projects/projectSlice'


function Home (){

    const dispatch = useDispatch();
    let projects = [];
    useEffect(() => {
        db.collection('projects').onSnapshot((snapshot) => {
            snapshot.docs.map((doc) => {
                
                // eslint-disable-next-line default-case
                switch(doc.data().type){
                    case 'clone': 
                    projects = [...projects, { id: doc.id, ...doc.data()}];
                    break; 
                }
            });
            dispatch(setProjects({
                project : projects,
            }))
        });
    }, []);


这是我的切片代码

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    project : null,
}

const projectSlice = createSlice({
    name: 'project',
    initialState, 
    reducers: {
        setProjects: (state,action) => {
            state.project = action.payload.project;
        },
    },
}); 

export const {setProjects} = projectSlice.actions 
export default projectSlice.reducer;

我想将数据从项目数组推送到切片的项目数组,这样我就可以在别处使用它,但当我使用调度时;它向我显示了这个错误

TypeError: Cannot read properties of undefined (reading 'type')

任何人都可以帮我解决我的错误,我堆了好久:(

您将 setProjects 导出为命名导出,但试图将其导入为默认导出。

import { useDispatch } from 'react-redux'
import db from '../firebase'
import setProjects from '../features/projects/projectSlice'

您需要像这样导入 setProjects...

import { setProjects } from '../features/projects/projectSlice'

More info 命名与默认导出。