简体   繁体   English

如何在 React(Next.js) 中使用具有不同查询字符串的另一个 GET 请求时维持来自 DB 的数据?

[英]How do I sustain data from DB while using another GET request with different query string in React(Next.js)?

I don't speak English very well.我英语说得不太好。 Please be understanding!请谅解!

First, please check my code!首先,请检查我的代码!


export default function DriveFolder() {

    const [clickFolderPk, setClickFolderPk] = useState(1);

    const viewFolder = async () => {
        const url = `/api/store/drive/view-folder?folderId=${clickFolderPk}`;
        await get(url)
            .then((res) => {
                console.log(res);
                setMainFolder(res.directChildrenFolders);
            })
            .catch((error) => {
                console.log(error);
            });
    };

    useEffect(() => {
        viewFolder();
    }, [clickFolderPk]);


    return (

        <div className={classes.driveFolder}>

            {mainFolder.map((main, key) => (
                <TreeView>
                    <TreeItem
                    onClick={() => setClickFolderPk(main.FOLDER_PK)}>
                        <TreeItem nodeId='10' label='OSS' />
                        <TreeItem nodeId='6' label='Material-UI'>
                            <TreeItem nodeId='7' label='src'>
                                <TreeItem nodeId='8' label='index.js' />
                                <TreeItem nodeId='9' label='tree-view.js' />
                            </TreeItem>
                        </TreeItem>
                    </TreeItem>
                </TreeView>
            ))}
        </div>
    );
}

I edited some code to make it clear.我编辑了一些代码以使其清楚。 (might misspelled) (可能拼写错误)

With this code, on the first rendering, since 'clickFolderPk' value is 1, I get the right data from DB.使用此代码,在第一次渲染时,由于“clickFolderPk”值为 1,我从 DB 中获取了正确的数据。

However, since I have subfolders within folders from 'clickFolderPk' value 1, I have to request another GET REQUEST to see my subfolders from root folders.但是,由于我在“clickFolderPk”值为 1 的文件夹中有子文件夹,我必须请求另一个 GET REQUEST 才能从根文件夹中查看我的子文件夹。

Here is the simple image that you can understand my situation better.这是一个简单的图像,您可以更好地了解我的情况。

第一次渲染

this is what I get from 'clickFolderPk' value 1.这是我从“clickFolderPk”值 1 中得到的。

However, when I press 'kikiki', GET request functions and render like this.但是,当我按下“kikiki”时,GET 请求功能并呈现如下。

用不同的PK重新渲染 . .

This is not the way I want to render things.这不是我想要渲染事物的方式。

I want every data from DB, however they don't disappear whenever I use different GET request with different PK number.我想要数据库中的每个数据,但是每当我使用具有不同 PK 号的不同 GET 请求时,它们都不会消失。

I want them stay on the screen and get the subfolders within them.我希望它们留在屏幕上并获取其中的子文件夹。

I'm struggling with this issue for quite a time.我在这个问题上挣扎了很长一段时间。

Your help will be really appreciated!!!!!您的帮助将不胜感激!!!!!!!

It's all about Nesting: Folders have sub-folders, etc and it goes on...这都是关于嵌套的:文件夹有子文件夹等,它继续......

Note: To break things down, I will answer from a React point of view disregarding how your backend api is structured or returns data.注意:为了分解问题,我将从 React 的角度回答,而不管您的后端 api 是如何结构化或返回数据的。

Basically there are two main approaches,基本上有两种主要方法,

Approach #1:方法#1:

The global state is a single source of truth for all the folders think of it like this:全局 state 是所有文件夹的单一事实来源,您可以这样想:


  const [allFolders, setAllFolders] = useState([
    {
      id: "1",
      name: "a-1",
      folders: [
        {
          name: "a-subfolder-1",
          folders: [{ name: "a-subfolder-subfolder-1" }],
        },
        { name: "subfolder-2" },
      ],
    },
  ]);

The problem is that any small update requires to mutate the entire state.问题是任何小的更新都需要改变整个 state。 So I will focus more on Approach #2所以我将更多地关注方法#2

Approach #2:方法#2:

There is the main tree that has child components, child components can expand and have children too:有子组件的主树,子组件也可以扩展并有子组件:

import { useEffect, useState } from "react";
import "./styles.css";

export default function DriveFolder() {
  const [folders, setFolders] = useState([
    { id: "1", name: "folder-a" },
    { id: "2", name: "folder-b" },
    { id: "3", name: "folder-c" }
  ]);

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {folders.map((folder) => {
        return <Folder key={folder.id} folder={folder} />;
      })}
    </div>
  );
}

const Folder = ({ parent = undefined, folder }) => {
  const [subfolders, setSubfolders] = useState([]);
  const [isOpened, setOpened] = useState(false);
  const hasSubfolders = subfolders.length > 0;

  useEffect(() => {
    // send request to your backend to fetch sub-folders

    // --------------- to ease stuff I will hard code it

    // with this you can limit the example of nest you wish
    const maxNestsCount = 5;
    const subfolderParent = parent || folder;
    const subfolder = {
      id: subfolderParent.id + "-sub",
      name: "subfolder-of-" + subfolderParent.name
    };
    const currentNestCount = subfolder.name.split("-sub").length;
    setSubfolders(currentNestCount < maxNestsCount ? [subfolder] : []);
    // -----------------------------
  }, []);

  const handleToggleShowSubFolders = (e) => {
    e.stopPropagation();
    if (!hasSubfolders) {
      return;
    }

    setOpened(!isOpened);
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        paddingHorizontal: 5,
        marginTop: 10,
        marginLeft: parent ? 20 : 0,
        backgroundColor: "#1678F230",
        cursor: hasSubfolders ? "pointer" : undefined
      }}
      onClick={handleToggleShowSubFolders}
    >
      {folder.name}

      <div style={{ display: isOpened ? "block" : "none" }}>
        {subfolders.map((subfolder) => (
          <Folder key={subfolder.id} parent={folder} folder={subfolder} />
        ))}
      </div>
    </div>
  );
};

Try it out:试试看:

Here is the output of the sample code above:这是上面示例代码的output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React(Next.js) 中的特定值有条件地从数据库中获取项目? - How do I conditionally get items from DB using specific value in React(Next.js)? 如何使用 Next.js 中的查询字符串参数进行路由? - How do I route with query string params in Next.js? 如何将文件上传请求从 Next.js API 传递到另一个 API? - How do I pass through a file upload request from a Next.js API to another API? 如何在广泛使用 React hooks 的同时利用 Next.js 服务器端渲染? - How do I take advantage of Next.js server-side rendering while using React hooks extensively? 在 React/Next.js 中,如何简单地将数据从一个页面的组件传递到另一个页面上的组件? - How can I simply pass data from a component one page to a component on another page in React/Next.js? 如何在 Next.js (React) 中制作粘性页脚 - How do I make a sticky footer in Next.js (React) 如何在 React(Next.js) 中的 useState 中获取多个文件? - How do I get mutliple files in useState in React(Next.js)? 如何在服务器上记录一些字符串并使用 Next.js 将其作为道具返回给组件? - How do I log some string on server and give it back to component as props using Next.js? 使用http获取express / react / next.js数据请求不获取任何数据 - Getting no data with express/react/next.js data request using http 如何在 Next.JS 中使用 getServerSideProps 从条带 api 获取用户数据? - How can I get user data from the stripe api with getServerSideProps in Next.JS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM