[英]How to pass string into react-router-dom Route as function?
I'm using React 16.11.0 and react-router-dom 5.1.2.我正在使用 React 16.11.0 和 react-router-dom 5.1.2。
I have an array of objects representing pages like this:我有一个代表这样的页面的对象数组:
const pages = [{ url: "/", component: "Home" }, {...}, ... ]
Update: Maybe I should mention this is from a JSON string so I don't get to determine the type of the values.更新:也许我应该提到这是来自 JSON 字符串,所以我无法确定值的类型。
I want to dynamically generate Routes in React by mapping over it:我想通过映射在 React 中动态生成路由:
import Home from './components/Home';
...
<BrowserRouter>
<div className="App">
<Switch>
{pages.map(page => (
<Route path={page.url} component={page.component} />
))}
</Switch>
</div>
</BrowserRouter>
page.url
works but URLs can be strings anyway. page.url
有效,但 URL 无论如何都可以是字符串。 page.component
is not loading properly, I think because it is a string whereas the imported Home
is a React function component. page.component
没有正确加载,我认为是因为它是一个字符串,而导入的Home
是一个 React function 组件。
I've tried to use eval()
and Function()
to convert the page.component
string into objects but they don't work.我尝试使用eval()
和Function()
将page.component
字符串转换为对象,但它们不起作用。
I've tried the docs and search engines but haven't been able to figure out a solution.我已经尝试过文档和搜索引擎,但无法找到解决方案。 Maybe I'm searching in the wrong places.也许我在错误的地方搜索。
Is this possible?这可能吗? How should I go about doing it?我应该怎么做 go 呢?
Actually you can even avoid importing modules - require
comes handy:实际上,您甚至可以避免导入模块 - require
很方便:
const pages = [{ url: "/", component: "Home" }, {...}, ...]
.map((obj) => (
{ url: obj.url, component: require(`./components/${obj.component}`).default }
);
And then following your logic:然后按照你的逻辑:
<Switch>
{pages.map(page => (
<Route path={page.url} component={page.component} />
))}
</Switch>
Try setting page.component to Home.尝试将 page.component 设置为 Home。
Instead of this:而不是这个:
const pages = [{ url: "/", component: "Home" }, {...}, ... ]
Try this:尝试这个:
const pages = [{ url: "/", component: Home }, {...}, ... ]
For the solution the only part you need is to create components dynamically, so对于解决方案,您唯一需要的部分是动态创建组件,所以
const pages = [
{ url: "/", component: Home },
{ url: "/about", component: About }
];
Keep in mind components should be defined before such as Home, About etc.请记住,组件应先定义,例如 Home、About 等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.