首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理单个反应组件中的多次使用效果

处理单个反应组件中的多次使用效果
EN

Stack Overflow用户
提问于 2022-01-30 22:18:09
回答 1查看 883关注 0票数 0

假设有一个与学校系统相关的反应应用程序:有多个班级,每个班级有多个教室,用户可以在第一个呈现时过滤班级和教室,页面将显示第一课堂和第一个教室中的学生。

然后,每当用户更改课堂时,页面必须更改教室,并显示与所选班级相关的第一个教室中的学生。

如果用户更改了教室,则页面必须加载所选教室中的学生。

我面临的两个问题是:

  • 是否可以在相同的使用效果下改变许多状态(选定的班级和联想的教室)。
  • 具有多种使用效果,第一种用于初始呈现,第二种用于更改类,第三种用于更改教室,当组件安装时,它将这三个钩子调用到一起。

在这种情况下,最好的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-31 18:27:47

根据对数据结构的描述,我们可以大致了解如何做到这一点。您不太了解这些结构,所以我使用了字符串ID(但可能在数组中有它们,可以使用整数索引)。

重要的部分是演示一个效果挂钩如何更新另一个效果挂钩所依赖的状态值,以及下一个效果挂钩如何响应和更新更多的状态。

然后,根据您的状态有条件地呈现不同的JSX。

如果您不熟悉TypeScript和TS语法,可以按照下面的操场链接操作,然后在右边看到普通编译的JavaScript

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)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70919443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档