简体   繁体   中英

How do I render folders within a folder in one component in React(Next.js)?

I'm not good at English so please be understanding.

First, please check my code.


const DriveFile = ({folderPk}) => {

    const [rootFolder, setRootFolder] = useState([])

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

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

    const [folderName, setFolderName] = useState('');

    const folderNameChange = (e) => {
        setFolderName(e.target.value)
    }

    const createFolder = () => {
        const url = '/api/store/drive/create-folder';
        const data = {
            folderName: folderName,
            parentPK: folderPk
        }
        if (folderName.length == 0) {
            alert('please write the folder name');
            return;
        }
        post(url, data)
        .then((res) => {
            console.log('파일 생성', res)
            setFolderName('');
        })
        .catch((error) => {
            console.log(error)
        })
    };

    return (
        <div className={styles.fileDiv}>

            <input value={folderName} onChange={folderNameChange}/><button onClick={createFolder}>ADD FOLDER</button>
            {
                rootFolder?.map((root) => (
                    <div>{root.FOLDER_NAME}</div>
                ))
            }
        </div>
    )
}

export default DriveFile

Here. this is my component.

The props, {folderPk}, is just a number that I selected from the top root folder then I use GET request using folderPk to render the direct child folders.

FYI, this is the UI.

在此处输入图像描述

So, when I click 'FOLDER 1', I get the specific FOLDER_PK. Then, I use it in different component to render subfolders like that.

However, my question is how can I get into a folder within a folder in a component.

For example, I'm trying to go into another folder when I click 'FOLDER 4, UNDER FOLDER 1' folder. I'm wondering can it be possible.

Is it possible in one component? or should I use different method?

Your answer will be really appreciated:!!!! :)

You should separate the code into components.

As a general advise: "Don't be afraid to split components into smaller components"

Use one component that knows the state (which is the current folder and it's subfolders), and other components which display the folders (based on the props), and provide buttons (with callbacks).

Here a vague example, just to illustrate basic idea (you will find a more appropriate component structure for your case):

const Folders = (props) => {   

    // (maybe your DriveFile of even another component would hold the state instead, or part of it)
    const [ currentFolderPk, setCurrentFolderPk ] = useState(0);
    const [ currentSubFolders, setCurrentSubFolders ] = useState([]);

    // ...

    return (
        <div className={styles.fileDiv}>
            <NewFolderInput onConfirm={ createFolder } />
            {
                currentSubFolders.map(( folder ) => (
                    <Folder
                        folderPk={ folder.folderPk }
                        folderName={ folder.FOLDER_NAME }
                        gotoFolderPk={ setCurrentFolderPk }
                    />
                ))
            }
        </div>
    )
}
const Folder = ({ folderName, folderPk, gotoFolderPk }) => {
    return (
        <div>
            { folderName }
            <button onClick={ () => gotoFolderPk( folderPk ) }>
                go to folder
            </button>
        </div>
    )
}

Even very small components often make sense:

const NewFolderInput = ({ folderName, folderNameChange, createFolder }) => {
    return (
        <input value={folderName} onChange={folderNameChange} />
        <button onClick={createFolder}>ADD FOLDER</button>
    );    
}

I'm not sure now where I would put the state and the API requests, I would decide that while working on it. Probably somewhere in an extra component between my and what ever is the parent of your.

Also I suggest to take naming variables very serious. You probably will be amazed how much that helps sometimes.

Eg the name of your state variable rootFolder might be not wrong is some sense, but just try renaming it to something like listOfSubfolders (or directChildrenFolders as you already used), and maybe the code magically will seem to have become quite a bit simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM