我目前正在尝试学习reactjs,我遇到了路由器 - react-dom,我试图创建一个动态路由器,并找到了这个解决方案How to Implement dynamic routing in routes.js for generated menu items in sidebar in universal react redux boilerplate by erikras解决方案选项2但我无法使其工作在我的最后。
这是我的Main.js
import React, { Component } from 'react';
import { Switch, Route, Link, Redirect, withRouter} from 'react-router-dom'
import Home from './Home'
import Inbox from './Inbox'
import Trash from './Trash'
import Order from './Order'
import Protected from './Protected'
import Login from './Login'
import Forums from './Forums'
import NoMatch from './NoMatch'
import Promos from './Promos'
import SiteRoutes from './Nav'
const Main = () => (
<main>
<Switch>
{SiteRoutes.public.map(route =>
<Route
key={route.index}
path={route.path}
exact={route.exact}
component={route.main}
/>
)}
</Switch>
</main>
)
export default Main;
这是我的Nav.js
import React, { Component } from 'react';
const Data = {
public :[
{
path: "/",
exact: true,
main: 'Home'
},
{
path: "/inbox",
main: 'Inbox'
},
{
path: "/trash",
main: 'Trash'
},
{
path: "/order/:value",
main: 'Order'
},
{
path: "/login",
main: 'Login'
},
{
path: "/forums",
main: 'Forums'
},
{
path: "/promos",
main: 'Promos'
}
]
};
export default Data;
我正在尝试从Nav.js映射并创建动态路由库,但我的问题是在component={route.main}
上创建路由,从而分配route.main
字符串值Nav.js似乎在我的情况下不起作用。我按照上面提到的链接进行了跟踪。
当我点击链接时,控制台错误是
index.js:2178 Warning: <Home /> is using uppercase HTML. Always use lowercase HTML tags in React.
我猜是因为它是一个字符串并且不会调用该组件,但是在上面提到的链接上似乎可以使用它们。我想知道我的代码中缺少什么?
提前致谢。
答案 0 :(得分:3)
字符串在传递给React.createElement
时会创建一个 DOM元素,而不是自定义组件,它们通常只有小写,因此会出现警告。相反,我建议只在Nav.js
本身存储组件类:
import Home from './Home'
import Inbox from './Inbox'
import Trash from './Trash'
import Order from './Order'
import Protected from './Protected'
import Login from './Login'
import Forums from './Forums'
import NoMatch from './NoMatch'
import Promos from './Promos'
const Data = {
public: [
{
path: "/",
exact: true,
main: Home
},
…
]
}
因此,当React Router在内部创建组件时,它将从组件类创建元素,而不是字符串。