javascript - React Routing Menu - 数据处理最佳实践
问题描述
我正在尝试为我的 React 应用程序创建一个菜单,如下所示:
列表本身很简单。但现在我有包含 2 个子组件的主要组件:
class App extends Component {
render() {
return (
<MenuBar/>
<DisplayPane/>
)
}
}
Component 包含所有的MenuBar
菜单构建逻辑,其中有一堆Link
组件。该DisplayPane
组件有几个Route
组件:
class DisplayPane extends Component {
render() {
return (
<Route path="/a" component={A} />
<Route path="/b" component={B} />
<Route path="/c" component={C} />
)
}
}
但现在我有一个问题,每当我想添加/删除/修改组件/路由时,我需要更新 2 个地方,这对我来说没有意义。
这是处理这种情况的反应方式,还是在 React 中做这种菜单的某种模式,所以维护更合理?
解决方案
对我来说似乎很好。但是,如果您想要一个更通用的方法,您可以创建一个单独的文件来存储实际的组件绑定及其路由并迭代以动态生成路由及其链接。你可以这样做:
路由.js
export default [
{
path : "/a",
component : A,
target : "",
isExact : true // You can add more objects to configure your route/link
},
{
path : "/b",
component : B,
target : "",
isExact : true
},
{
path : "/c",
component : C,
target : "",
isExact : true
},
]
您可以导入组件Route.js
并将它们映射到component
属性。Route.js
您可以在您的内部导入DisplayPane
并MenuBar
遍历它以生成动态路由。
DisplayPane.js
class DisplayPane extends Component {
render() {
return routesObj.map((route,index)=> {
return <Route key={index} exact={route.isExact} path={route.path} component={route.component}/>
})
}
}
同样,您也可以在其中导入相同的对象MenuBar
并使用map
它来渲染Link
. 这样,您只需要在数组中创建另一个对象,map 就会为您处理它。
推荐阅读
- bash - Terraform init 问题:命令行参数过多
- java - Rapidclipse 和 Microstream:需要延迟加载到表中的示例
- javascript - 无法在控制台上使用 hbs && 在 express 中添加 CSS 和 JS 文件:未捕获的 SyntaxError: Unexpected token '<'
- python - 在 Python 中:一次将 QtableWidget 中的所有条目插入数据库表
- api - JWT Token Security 漏洞和可能的解决方案请求
- python - IF 条件更新值取决于外部或内部间隔
- amazon-athena - AWS Athena(Presto)如何将值是数组的映射转置为行
- javascript - 在 Promise 之前调用 setTimeout
- javascript - 警告:在 Formik 中从 submitForm() [TypeError: undefined is not an object (evalating '_props$field.open')] 中捕获了一个未处理的错误
- python - 创建一个没有无限循环的程序