假设有一个与学校系统相关的反应应用程序:有多个班级,每个班级有多个教室,用户可以在第一个呈现时过滤班级和教室,页面将显示第一课堂和第一个教室中的学生。
然后,每当用户更改课堂时,页面必须更改教室,并显示与所选班级相关的第一个教室中的学生。
如果用户更改了教室,则页面必须加载所选教室中的学生。
我面临的两个问题是:
在这种情况下,最好的方法是什么?
发布于 2022-01-31 18:27:47
根据对数据结构的描述,我们可以大致了解如何做到这一点。您不太了解这些结构,所以我使用了字符串ID(但可能在数组中有它们,可以使用整数索引)。
重要的部分是演示一个效果挂钩如何更新另一个效果挂钩所依赖的状态值,以及下一个效果挂钩如何响应和更新更多的状态。
然后,根据您的状态有条件地呈现不同的JSX。
如果您不熟悉TypeScript和TS语法,可以按照下面的操场链接操作,然后在右边看到普通编译的JavaScript
import {default as React, useEffect, useState} from 'react';
// Some arbitrary types for this example
type Student = {
id: string;
};
type Classroom = {
id: string;
students: { [id: string]: Student };
};
type Class = {
id: string;
classRooms: { [id: string]: Classroom };
};
// Functions which get the data from your API. Imagine these are in another file and you import them:
// imoprt {fetchClass, fetchClassroom} from './api';
declare function fetchClass (id: string): Promise<Class>;
declare function fetchClassroom (id: string): Promise<Classroom>;
// Determine if a value exists (is not null or undefined)
function exists <T>(maybe: T): maybe is NonNullable<T> {
return maybe != null;
}
// The component
function Example () {
const [classId, setClassId] = useState<string>();
const [currentClass, setCurrentClass] = useState<Class>();
const [classroomId, setClassroomId] = useState<string>();
const [currentClassroom, setCurrentClassroom] = useState<Classroom>();
useEffect(() => {
if (!exists(classId)) return;
(async () => {
setCurrentClass(await fetchClass(classId));
setClassroomId('id_of_first_classroom');
})();
}, [classId]);
useEffect(() => {
if (!exists(classroomId)) return;
(async () => {
setCurrentClassroom(await fetchClassroom(classroomId));
})();
}, [classroomId]);
if (exists(currentClass)) {
if (exists(currentClassroom)) {
// return JSX created with the currentClass and currentClassroom data
}
else {
// return JSX created with just the currentClass data (e.g. choose a classroom based on a list of classroom IDs)
}
}
// return some JSX to get started (e.g. choose a class based on a list of class IDs)
}https://stackoverflow.com/questions/70919443
复制相似问题