首页 > 解决方案 > 如何处理 React Router 递归路径?

问题描述

我正在开发一个反应应用程序,我正在实现文件系统,如上传文件和创建文件夹等(小保管箱)。我正在通过此链接阅读有关反应路由器递归路径的信息:https ://reacttraining.com/react-router/web/example/recursive-paths 组件正在同一页面上呈现。我想做这种递归模式,而不是在同一页面上重新渲染,我只想渲染最新的路由数据,就像在 cpanel 或 Dropbox 等服务器上使用文件系统时一样。任何帮助,将不胜感激。

应用程序.js

    <Switch>
           <Route
           path={"/files/:title"} component={FolderDetail} />
   </Switch>

FolderDetail.js

import React, { useState } from "react";
import { Switch, Route } from "react-router-dom";
import { Row, Col } from "reactstrap";
import UploadOptionsSidebar from "../components/Sidebar/UploadOptionsSidebar";
import BrowseFiles from "../components/BrowseFiles/BrowseFiles";
import CreateFolder from "../components/CreateFolder/CreateFolder";
import { AppContext } from "../components/Context/main";

const FolderDetail = ({ match, child }) => {
    const { files } = React.useContext(AppContext);
    const [createFolder, setCreateFolder] = useState(false);

    const getFiles = () => {
        return files.filter((file) => file.parent === match.params.title);
    };

    return (
        <div>
            <React.Fragment>
                <h3>
                    Files >{" "}
                    <span className={"text-muted"}>{match.params.title}</span>{" "}
                </h3>
                <Row className={"mt-5 mx-0"}>
                    <Col md={"8"}>
                        <BrowseFiles files={getFiles()} />
                    </Col>
                    <Col md={"3"}>
                        <UploadOptionsSidebar
                            openCreateFolder={() => setCreateFolder(true)}
                        />
                    </Col>
                </Row>
                <CreateFolder
                    open={createFolder}
                    parent={match.params.title}
                    toggle={() => setCreateFolder(false)}
                />
            </React.Fragment>

            <Switch>
                <Route
                    path={`${match.url}/:title`}
                    render={() => <FolderDetail match={match} child={true} />}
                />
            </Switch>
        </div>
    );
};

export default FolderDetail;

标签: javascriptreactjsreact-router

解决方案


如何在组件中使用非精确路径,例如<Route path="/files" component={Files} />并使用this.props.location.pathname(请参阅位置文档Files使用正则表达式从路径中提取您需要的数据,并且只呈现满足您需要的内容(例如相对于路径的最后一部分)?


推荐阅读