我试图从存储的状态显示student
和teacher
的长度。但是为什么当使用多个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;
}
}
1条答案
按热度按时间djmepvbi1#
您在不同的reducer中使用相同的动作类型。这意味着当您加载/创建
teachers
时,也会更新students
,反之亦然。对多个缩减者中出现的类似活动使用不同的类型。更新活动创建者中的活动类型,同时更新缩减者:
另外,
useEffect
块在JSX渲染之后执行,并且只有在此之后才会更新ref。更新ref不会导致重新渲染,因此您可能始终具有先前ref的值。您不需要ref(以及useEffect
),只需要从选择器获得的值,例如: