gpt4 book ai didi

javascript - React Route - 从 JSON 对象中的字符串渲染路由中的组件

转载 作者:行者123 更新时间:2023-12-02 21:03:30 25 4
gpt4 key购买 nike

我正在尝试与我创建的 JSON 文件中的组件名称进行比较来渲染 React 组件。例如,我想在我的 Route 组件内渲染 TestSection 组件。

这是使用“react-router-dom”提供的路由组件。

这是我尝试创建动态路线的一个例子,但我完全困惑为什么这行不通:

(DynamicNavigaitonSwitcher.js)

import { BrowserRouter as Route, Switch } from "react-router-dom";

navigation = [
["Explore", "/", "Explore", false],
["Profile", "/profile/", "TestSection", false],
["Messages", "/messages/", "TestSection", false],
["Listings", "/listings/", "TestSection", false],
["Settings", "/settings/","TestSection", false],
["Login", "/login/","TestSection", false],
["Sign-up", "/signup/", "TestSection", false]
]

const Explore = () => {
return (
<div>
<h1>Explore !!</h1>
</div>
)
}

const TestSection = () => {
return (
<p>Hey</p>
)
}

const Components = {
testsection: TestSection,
explore: Explore
};

const DynamicRoutes = navigation.map((navItem) => {
return (
<Route path={navItem[1]} key={navItem[0]} name={navItem[0]} component={Components[navItem[2]]}/>
)
}
);

const DynamicNavigationSwitcher = () => {
return (
<div>
<Switch>
{DynamicRoutes}
</Switch>
</div>
)
}

export default DynamicNavigationSwitcher;

最佳答案

存在一些语法错误:

  • 您应该创建类似的 DynamicRoutes 组件并返回导航 map 。
  • 组件:按键错误且与导航项位置 2 不同
  • BrowserRouter 你应该把它放在index.js 中并包裹起来//如果你有的话,用div 来改变这段代码中的BrowserRouter 就可以了
  • Route 元素用于创建路线

测试此代码,我纠正了以前的错误,它对我有用:

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

const navigation = [
["Explore", "/", "explore", false],
["Profile", "/profile/", "testsection", false],
["Messages", "/messages/", "testsection", false],
["Listings", "/listings/", "testsection", false],
["Settings", "/settings/", "testsection", false],
["Login", "/login/", "testsection", false],
["Sign-up", "/signup/", "testsection", false]
];

const Explore = () => {
return (
<div>
<h1>Explore !!</h1>
</div>
);
};

const TestSection = () => {
return <p>Hey</p>;
};

const Components = {
testsection: TestSection,
explore: Explore
};

const DynamicRoutes = () => {
return navigation.map(navItem => {
return (
<Route
path={navItem[1]}
key={navItem[0]}
name={navItem[0]}
component={Components[navItem[2]]}
/>
);
});
};

const DynamicNavigationSwitcher = () => {
return (
<BrowserRouter>
<Switch>
<DynamicRoutes />
</Switch>
</BrowserRouter>
);
};

export default DynamicNavigationSwitcher;

关于javascript - React Route - 从 JSON 对象中的字符串渲染路由中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com