带有模板区域的动态参数 [英] Dynamic parameters with template regions
问题描述
尝试使用 React-Router v4 设置 React 应用程序.我需要使用动态路由参数进行导航,以及使用采用动态路由参数的组件来定位我的应用程序模板区域的能力.根据 v4 文档,我需要像这样定义我的路线:
const 路由 = [{准确:真实,路径:'/vpcs',navLevel2: () =><VpcList></VpcList>,主要内容:() =><h1>你好 VPC</h1>},{准确:真实,路径:'/vpcs/:vpcName',navLevel2: () =><VpcList></VpcList>,主要内容:() =><Vpc></Vpc>}]
然后我可以这样做:
<div><导航><ul><li><NavLink to="/vpcs">Vpcs</NavLink></li></nav><导航>{routes.map((route, index) => (<路线键={索引}路径={route.path}精确={route.exact}组件={route.navLevel2}/>))}</nav><主要>{routes.map((route, index) => (<路线键={索引}路径={route.path}精确={route.exact}组件={route.mainContent}/>))}</main>
</BrowserRouter>
但是,似乎没有办法将 :vpcName
的值传递给需要它的 Vpc
组件.当我点击路由 /vpc/my-vpc-name
控制台日志
未捕获的类型错误:无法读取新 Vpc 上未定义的属性参数"...
为了看看我必须使用什么,代替 component={route.mainContent}
我试过:
component={() =>(<p>{JSON.stringify(arguments)}</p>)}
结果是
{"0":{"i":480,"l":false,"exports":{}},"1":{}}
...这并不令人鼓舞.
我该怎么办?我是否需要回退到 v3 才能在使用动态路由参数的同时使模板区域工作?
您的组件实际上是通过 props 接收参数的,只是您没有使用它们.尝试执行以下操作: mainContent: props =><div>{props.match.params.vpcName}</div>
我在这里为你做了一个小例子:https://codesandbox.io/s/v61p95k850
Trying to set up a react app with React-Router v4. I require navigation with a dynamic route param, and the ability to target areas of my app template with a component that takes the dynamic route param. According to the v4 docs, I need to define my routes like this:
const routes = [
{
exact: true,
path: '/vpcs',
navLevel2: () => <VpcList></VpcList>,
mainContent: () => <h1>Hello VPCs</h1>
},
{
exact: true,
path: '/vpcs/:vpcName',
navLevel2: () => <VpcList></VpcList>,
mainContent: () => <Vpc></Vpc>
}
]
Then I can do:
<BrowserRouter basename="/">
<div>
<nav>
<ul>
<li><NavLink to="/vpcs">Vpcs</NavLink></li>
</ul>
</nav>
<nav>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.navLevel2}
/>
))}
</nav>
<main>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.mainContent}
/>
))}
</main>
</div>
</BrowserRouter>
However, it seems there's no way to pass the value for :vpcName
to the Vpc
component, which requires it. When I hit the route /vpc/my-vpc-name
the console logs
Uncaught TypeError: Cannot read property 'params' of undefined at new Vpc ...
To see what I have to work with, in place of component={route.mainContent}
I've tried:
component={() => (<p>{JSON.stringify(arguments)}</p>)}
And that yielded
{"0":{"i":480,"l":false,"exports":{}},"1":{}}
...which is not encouraging.
What do I do? Do I need to rewind to v3 to get template regions to work while ueing dynamic route params??
Your component actually receives the params via props, you are just not using them. Try doing something like: mainContent: props => <div>{props.match.params.vpcName}</div>
I made a small example for you here: https://codesandbox.io/s/v61p95k850
这篇关于带有模板区域的动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!