redux 如何在多个dispatch()中使用useSelector()

w3nuxt5m  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(188)

我试图从存储的状态显示studentteacher的长度。但是为什么当使用多个dispatch()时,它与前一个dispatch()重叠,因此显示错误的长度。
在父组件中,我使用了多个dispatch()

const dispatch = useDispatch()

    useEffect(() => {
      dispatch(getStudents());
      dispatch(getTeachers());
      dispatch(getSections());
    }, [dispatch])

<StudentInfo/>中,我尝试访问状态并显示它。

export default function StudentInfo() {
    const students = useSelector((state) => state.students);

    //try
    const studentsRef = React.useRef(students);

    useEffect(() => {
        studentsRef.current = students;
    }, [students])

    return(
        <>
        <Box style={{ paddingTop: '1.5rem', height: '2rem'}}>
            <SchoolSharpIcon sx={{fontSize: '40px'}} />
        </Box>
        <Box style={{fontSize: '1rem'}}>
            Number of Students enrolled: {studentsRef.current.length}
        </Box>
        </>
    )
}

<TeacherInfo/>中的方式相同

export default function TeacherInfo() {

    const teachers = useSelector((state) => state.teachers);

    //try
    const teachersRef = React.useRef(teachers);

    useEffect(() => {
        teachersRef.current = teachers;
    }, [teachers])

    return(
        <>
        <Box style={{ paddingTop: '1.5rem', height: '2rem'}}>
            <AccountBoxSharpIcon sx={{fontSize: '40px'}} />
        </Box>
        <Box style={{fontSize: '1rem'}}>
            Number of Teachers: {teachersRef.current.length}
        </Box>
        </>
    )
}

它正在显示这错误的长度.例如,这<StudentInfo/>正在显示这长度的teacher状态并且反之亦然

export function students (students = [], action) {
switch (action.type) {
    case 'FETCH_ALL':
        console.log(action.payload)
        console.log("students?")
        return action.payload;
    case 'CREATE':
        return [...students, action.payload];

    default:
        return students;
}

}

export function teachers (teachers = [], action) {
switch (action.type) {
    case 'FETCH_ALL':
        console.log(action.payload)
        console.log("teachers?")
        return action.payload;
    case 'CREATE':
        return [...teachers, action.payload];

    default:
        return teachers;
}

}

djmepvbi

djmepvbi1#

您在不同的reducer中使用相同的动作类型。这意味着当您加载/创建teachers时,也会更新students,反之亦然。
对多个缩减者中出现的类似活动使用不同的类型。更新活动创建者中的活动类型,同时更新缩减者:

export function students (students = [], action) {
  switch (action.type) {
    case 'students/FETCH_ALL':
    ...
    case 'students/CREATE':
    ...
    default:
        return students;
}

export function teachers (teachers = [], action) {
  switch (action.type) {
    case 'teachers/FETCH_ALL':
    ...
    case 'teachers/CREATE':
    ...

    default:
        return teachers;
}

另外,useEffect块在JSX渲染之后执行,并且只有在此之后才会更新ref。更新ref不会导致重新渲染,因此您可能始终具有先前ref的值。您不需要ref(以及useEffect),只需要从选择器获得的值,例如:

Number of Students enrolled: {students.length}

Number of Teachers: {teachers.length}

相关问题