【问题标题】:React Router Dom routes and sub-routesReact Router Dom 路由和子路由
【发布时间】:2018-01-28 20:21:21
【问题描述】:

React-router-dom / ReactJS 初学者一般在这里。

我有一些可以工作的路由器代码,我认为可以稍微清理一下,但到目前为止,这样做的尝试都失败了。我在这方面的知识肯定有一些空白。我翻阅了类似的问题,这些问题帮助我扩大了理解,但目前我还没有成功地将这些问题联系起来。

以下代码似乎运行良好,但我对所有管理路由重复的“/admin”前缀感到厌烦。

<BrowserRouter>
    <div>
        <div className="nav-bar">
            <ul>
                <li><Link to="/admin">Home</Link></li>
                <li><Link to="/admin/content">Content</Link></li>
                ...
            </ul>
        </div>
        <div className="nav-content">
            <Route exact path="/admin" component={AdminHome}/>
            <Route path="/admin/content" component={AdminContent}/>
            ...
        </div>
    </div>
</BrowserRouter>

但是,将“嵌套”路由移动到子路由元素不起作用。 JavaScript 控制台吐出错误消息“警告:您不应在同一路由中使用 and;将被忽略。”

<Route exact path="/admin" component={AdminHome}>
    <Route path="/content" component={AdminContent}/>
    ...
</Route>

任何建议将不胜感激。我已经阅读了许多 SO 答案,并找到了一些选项,例如,我可以使用 &lt;Route path="/admin/:whatever" render={() =&gt; (...)}/&gt;,但目前看来这不是正确的路径。

这样做的原因是,我最终需要在树的下方进一步使用路由参数,例如对于类似于 /admin/content/:content_type/:identifier 的 URI,理想情况下,我的 AdminContent 组件将不知道其父路由匹配。

如果我离基地很远,也请随时告诉我,如果有任何文件你认为会告诉我我很想阅读它。

再次干杯,再次感谢!

【问题讨论】:

标签: reactjs react-router react-router-dom


【解决方案1】:

感谢上面的 Christopher 提供了一些优秀文档的链接。

根据链接的文档,以下更改现已启动并运行:

{/* top-level route declaration */}
<div className="nav-content">
    {/* note the removal of the exact property here */}
    <Route path="/admin" component={AdminRoutes}/>
</div>

{/* "sub-routes" (possible poor nomenclature) */}
const AdminRoutes = ({ match }) => (
    <div>
        {/* note the addition of the exact property here */}
        <Route exact path={match.url} component={AdminHome}/>
        <Route path={match.url + "/content"} component={AdminContent}/>
        <Route path={match.url + "/data-store"} component={AdminDataStore}/>
        <Route path={match.url + "/search"} component={AdminSearch}/>
        <Route path={match.url + "/communicate"} component={AdminCommunicate}/>
        <Route path={match.url + "/promote"} component={AdminPromote}/>
        <Route path={match.url + "/measure"} component={AdminMeasure}/>
        <Route path={match.url + "/experimental"} component={AdminExperimental}/>
    </div>
)

进一步扩展:在我目前看到的所有使用嵌套路由和入站“匹配”参数的示例中,它们的实现方式如上,即const X = ({match}) =&gt; (...)

但是定义一个真正的 React.Component 子类是可能的,并且可能有用,其中参数匹配仍然可以通过this.props 获得。

class Content extends React.Component {

    // usage example
    render() {

        // `match` is available via inbound props
        console.log(this.props.match);

        return (
            <p>Match is {this.props.match.url}</p>
        )
    }
}

此时我想重申一下,我是 ReactJS 初学者...如果我在做一些愚蠢的事情,请告诉我 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 2019-05-30
    • 2018-06-04
    • 1970-01-01
    • 2022-10-16
    • 2022-07-07
    • 2021-11-03
    相关资源
    最近更新 更多