具有模板区域的动态参数

Dynamic parameters with template regions

正在尝试使用 React-Router v4 设置 React 应用程序。 我需要使用动态路由参数进行导航,并且能够使用采用动态路由参数的组件来定位我的应用程序模板的区域。根据 v4 文档,我需要这样定义我的路线:

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>
    }
]

那我可以做:

<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>

但是,似乎无法将 :vpcName 的值传递给需要它的 Vpc 组件。当我点击路由 /vpc/my-vpc-name 时,控制台记录

Uncaught TypeError: Cannot read property 'params' of undefined at new Vpc ...

要查看我必须使用什么,代替 component={route.mainContent} 我试过:

component={() => (<p>{JSON.stringify(arguments)}</p>)}

这就产生了

{"0":{"i":480,"l":false,"exports":{}},"1":{}}

...这并不令人鼓舞。

我该怎么办?我是否需要倒退到 v3 才能在使用动态路由参数时让模板区域工作?

而不是在 <Route> 标签中使用 component,您应该使用 render 接受函数,然后您可以在其中使用像 {() => (<p>{JSON.stringify(arguments)}</p>)} 这样的函数.

Here is a link to their doc

您的组件实际上通过道具接收参数,您只是没有使用它们。尝试做类似的事情:mainContent: props => <div>{props.match.params.vpcName}</div>

我在这里为你做了一个小例子:https://codesandbox.io/s/v61p95k850