【发布时间】:2020-04-15 23:37:07
【问题描述】:
我试图弄清楚如何构造一个路由器,以便为管理员、用户和公共使用不同的路由。
我看到this post 和描述钥匙斗篷的答案 - 但我无法理解它。
我看过这个code sandbox,这对我来说看起来很合乎逻辑,但我在整合它时遇到了麻烦。
我有一个常量文件,我将路由定义为:
export const NEWBLOG = '/admin/newblog';
export const VIEWBLOG = '/viewblog';
我将其导入到我的 App.js 中,然后想为 Admin、User 和 Public 定义不同的 const,如下所示:
import * as ROUTES from '../../util/constants/Routes';
import NewBlog from '../../components/blog/admin/New';
// admin routes
const Admin = ({ match }) => (
<React.Fragment>
<Route path={`${match.path}/${ROUTES.NEWBLOG}`} component={NewBlog} />
<Route path={`${match.path}/2`} render={() => <h2>test</h2>} />
</React.Fragment>
);
// authenticated user routes
const Other = ({ match }) => (
<React.Fragment>
<Switch>
<Route path={`${match.path}/2`} render={() => <h2>one</h2>} />
<Route path={`${match.path}/2`} render={() => <h2>two</h2>} />
</Switch>
</React.Fragment>
);
// public routes
const Public = ({ match }) => (
<React.Fragment>
<Switch>
<Route path={`${match.path}/2`} render={() => <h2>one</h2>} />
<Route path={`${match.path}/2`} render={() => <h2>two</h2>} />
</Switch>
</React.Fragment>
);
然后在路由器语句中我有:
const App = () => (
<Router>
<Navigation />
<Switch>
<Route path="/a" component={Admin} />
<Route path="/u" component={Other} />
<Route path="/p" component={Public} />
<Route
component={({ location }) => {
return (
<div
style={{
padding: "50px",
width: "100%",
textAlign: "center"
}}
>
<ErrorMessage />
</div>
);
}}
/>
</Switch>
</Router>
);
export default App;
这一切都有效,直到我尝试使用 Admin 常量的反引号部分内的路由常量。
我似乎无法使用这种方法。
任何人都可以提供参考资料来源以找到解决方法吗?
【问题讨论】:
-
怎么不工作?为什么不为
NEWBLOG常量定义特定的路由部分,比如const NEWBLOG = 'newblog'而不是const NEWBLOG = '/admin/newblog'? -
我在代码中是这样定义的,但只是想在示例中使其更清晰。停止它工作的部分是后面的 ROUTES.NEWBLOG 标记
-
它有效,你可以检查它here,它在大括号字符串文字中有
ROUTES.NEWBLOG。我看到的问题是您在NEWBLOG变量中定义了整个路由,例如/admin/newblog。
标签: reactjs react-router