Dynamic parameters with template regions

北城余情 提交于 2019-12-23 04:55:27

问题


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


回答1:


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




回答2:


Instead of using component in your <Route> tag, you should be using render which takes the function and you can then use your function like {() => (<p>{JSON.stringify(arguments)}</p>)} inside it.

Here is a link to their doc



来源:https://stackoverflow.com/questions/47255363/dynamic-parameters-with-template-regions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!