reactjs - React:对不同的路线使用不同的布局
问题描述
我遇到了一个有点奇怪的问题,尝试将我的组件拆分为使用两种不同的布局。我有 2 个布局:我PublicLayout
的路线定义如下:Layout
App.js
render() {
return (
<ApolloProvider client={client}>
<Layout>
<Route path="/articles" component={ArticlesIndex} exact={true} />
<Route
path="/articles/create"
component={ArticlesCreate}
exact={true}
/>
<Route
path="/articles/edit/:id"
component={ArticlesEdit}
exact={true}
/>
</Layout>
<PublicLayout>
<Route exact path="/" component={Home} exact={true} />
<Route
path="/articles/view/:id"
component={ArticlesView}
exact={true}
/>
</PublicLayout>
</ApolloProvider>
);
}
这是Layout
看起来的样子:
<div className="container">
<Grid fluid>
<Row>
<Col sm={12}>
{this.props.children}
</Col>
</Row>
</Grid>
</div>
我在标签内的所有路由/组件都PublicLayout
按预期呈现和运行。但是,使用我的组件的所有路由/组件Layout
都按预期呈现,然后PublicLayout
在它们下方呈现。我猜 PublicLayout
这些页面中包含它,因为它在该部分之后出现没有限定条件Layout
。我怎样才能克服这个问题,只PublicLayout
在它包含的路线上渲染?
感谢所有帮助。
更新:我已经通过使用以下方法解决了我的问题,这使我可以在每条路线的基础上任意定义每条路线的布局:
function renderWithLayout(Component, Layout, props) {
return <Layout><Component {...props}/></Layout>
}
export default class App extends Component {
displayName = App.name;
render() {
return (
<ApolloProvider client={client}>
<Route
path="/articles"
render={(props) => renderWithLayout(ArticlesIndex, Layout, props)}
exact={true}
/>
<Route
path="/articles/create"
render={(props) => renderWithLayout(ArticlesCreate, Layout, props)}
exact={true}
/>
<Route
path="/articles/edit/:id"
render={(props) => renderWithLayout(ArticlesEdit, Layout, props)}
exact={true}
/>
<Route
path="/"
render={(props) => renderWithLayout(Home, PublicLayout, props)}
exact={true}
/>
<Route
path="/articles/view/:id"
render={(props) => renderWithLayout(ArticlesView, PublicLayout, props)}
exact={true}
/>
</ApolloProvider>
);
}
}
解决方案
使用条件渲染。让我们假设loggedIn
您使用它来跟踪用户是否已通过身份验证。
render() {
return {
<ApolloProvider client={client}>
{ loggedIn ? (
<Layout>
<Route path="/articles" component={ArticlesIndex} exact={true} />
<Route
path="/articles/create"
component={ArticlesCreate}
exact={true}
/>
<Route
path="/articles/edit/:id"
component={ArticlesEdit}
exact={true}
/>
</Layout>
) : (
<PublicLayout>
<Route exact path="/" component={Home} exact={true} />
<Route
path="/articles/view/:id"
component={ArticlesView}
exact={true}
/>
</PublicLayout>
)}
</ApolloProvider>
);
}
对于其他示例和解决方案https://reactjs.org/docs/conditional-rendering.html
推荐阅读
- pandas - 使用熊猫时的Python KeyError
- delphi - 无法使用 TDBCheckbox 更新数据库中的值
- r - 我想知道如何制作一个由 R 中的几个单词组成的关键词的术语文档矩阵
- c# - 键入对象时问号有什么作用?.field?
- python - Pygame Sprite 透明度碰撞
- python - 如何从 dbpedia 查询实体类型
- mysql - 需要自定义id
- javascript - 如何在 Vue.js 中格式化当前日期格式
- java - 如果在无限循环中声明了任何变量/对象,那么关于内存的情况会怎样?
- tensorflow - TensorFlow 指数衰减学习率似乎不起作用