问题描述
假设我有一个名为Component1
的React组件,它根据提供的数据进行绘图-
import data_A from "./some/folder/A";
import data_B from "./some/folder/B";
.
.
.
import data_Z from "./some/folder/Z";
const Component1 = (props) => {
var data = /* decide which data to load using props,will come from a nav link click event */
return(/* render component with data */);
}
const Component1 = React.lazy(() => import("./views/components/Component1"));
routes = [
{ path: "/components",name: "Component1",component: Component1,}
// there are more components but they are not relevant here.
];
然后我像这样构建<Switch/>
:
<Switch>
{routes.map((route,idx) => {
return(route.component && (
<Route key={idx} path={route.path} exact={route.exact} name={route.name}
render={(props) => (<route.component {...props} />)}
/>
));
})}
<Redirect from="/" to="/components" />
</Switch>
在我的应用程序中,我有一个导航栏,该导航栏是根据变量中指定的对象列表动态构建的。在这里,每个导航项都指定了我们要访问的数据-
var navDataList = [
{ _tag: "CSidebarNavItem",name: "Data A",to: "/components" },{ _tag: "CSidebarNavItem",name: "Data B",.
.
.
{ _tag: "CSidebarNavItem",name: "Data Z",]
并以此创建-
<CSidebarNav>
<CCreateElement items={navDataList} components={{CSidebarNavItem}} />
</CSidebarNav>
所以我基本上想做的是,当用户单击导航链接时,使用相同的组件data_A
处理data_B
,data_C
和Component1
等分别为Data A
,Data B
和Data C
。
我了解到的是,我已经指定了要在navList
内部处理的数据对象作为道具。但是我不知道该怎么办。
我该如何解决这个问题?
有关CoreUI React组件的文档在这里:CSidebarNavItem
,CSidebarNav
,CCreateElement
。
某种可行的解决方案:
在navDataList
内,如果我指定了这些参数,则可以从Component1
进行访问:
var navDataList = [
{ _tag: "CSidebarNavItem",to: {
pathname: "/components",hash: "data_A_will_be_default",params: { data: "data_A" },},hash: "data_B",params: { data: "data_B" },...
];
,然后在Component1
内进行标识:
const Component1 = (props) => {
var data = data_A; // default data to process
if (props.location.params && props.location.params.data) {
if (props.location.params.data === "data_B") {
data = data_B;
}
}
return(/* render component with data */);
}
但是它没有反应,并且有滞后。 params.data
不会立即更新。
解决方法
我将定义一个“组件”路由路径,该路径将数据作为路由参数并在Function_call_id | time_taken_for_function_call(seconds)
1 7
2 5
3 1
4 1
中进行访问。
路线-使用路线参数Component1
"/components/:data"
链接-链接到具有指定数据的特定路径
routes = [
{ path: "/components/:data",name: "Component1",component: Component1,}
// there are more components but they are not relevant here.
];
通过match或Route props react hook访问useParams参数
var navDataList = [
{ _tag: "CSidebarNavItem",name: "Data A",to: "/components/A" },{ _tag: "CSidebarNavItem",name: "Data B",to: "/components/B" },.
.
.
{ _tag: "CSidebarNavItem",name: "Data Z",to: "/components/Z" },];
或
const Component1 = props => {
const { data } = props.match.params;
...
}