简体   繁体   English

使用反应路由器,如何使用路由配置传递组件道具?

[英]Using react router, how can I pass component props using a route config?

I am trying to achieve the following using a single router config array.我正在尝试使用单个路由器配置数组实现以下目标。 The thing to note here is that I have a state variable, storeName , which I am passing to the CategoryPage component.这里要注意的是,我有一个状态变量storeName ,我将它传递给CategoryPage组件。

import React, { useState } from 'react'
import { Switch, Route, BrowserRouter } from 'react-router-dom'
import { Navigation } from './Navigation'
import { HomePage } from './HomePage'
import { CategoryPage } from './CategoryPage'
import { ProductPage } from './ProductPage'
import { PageNotFoundPage } from './404Page'

export function App() {
    const [storeName, setStoreName] = useState('My Store')

    return (
        <div>
            <h1>{storeName}</h1>
            <BrowserRouter>
                <Switch>
                    <Route path="/category">
                        <CategoryPage storeName={storeName} />
                    </Route>
                    <Route path="/product">
                        <ProductPage />
                    </Route>
                    <Route path="/" exact>
                        <HomePage />
                    </Route>
                    <Route path="*">
                        <PageNotFoundPage />
                    </Route>
                </Switch>
            </BrowserRouter>
        </div>
    )
}

If I was to switch to using a route config object like so...如果我要切换到像这样使用路由配置对象...

const routeConfig = [
    {
        path: '/',
        exact: true,
        component: HomePage,
    },
    {
        path: '/category',
        exact: false,
        component: CategoryPage,
    },
    // ...
]

// ...

<Switch>
    {routeConfig.map((route, i) => {
        return (
            <Route
                path={route.path}
                exact={route.exact}
                key={i}
            >
                <route.component />
            </Route>
        )
    })}
</Switch>

...what would be the most appropriate way to pass down props keeping in mind each component might need different props? ...记住每个组件可能需要不同的道具,传递道具的最合适方法是什么?

I suppose I could try to make the component key of the route config items a function which accepts every prop and then tries to map it to the component being returned.我想我可以尝试使路由配置项的component键成为一个函数,该函数接受每个道具,然后尝试将其映射到正在返回的组件。 I'm not sure if this is the right way though.我不确定这是否是正确的方法。

Thanks!谢谢!


Update #1更新 #1

So I tried instead to return the component from the route config array like so:所以我尝试从路由配置数组中返回组件,如下所示:

const routeConfig = [
    {
        path: '/',
        exact: true,
        component: (props) => <HomePage {...props} />,
    },
    {
        path: '/category',
        exact: false,
        component: (props) => {
            return <CategoryPage {...props} />
        },
    },
]

// ...

const [storeName, setStoreName] = useState('My Store')

// ...

<Switch>
    {routeConfig.map((route, i) => {
        return (
            <Route
                path={route.path}
                exact={route.exact}
                key={i}
            >
                {route.component({ storeName })}
            </Route>
        )
    })}
</Switch>

This is working, but every component now would have every prop.这是有效的,但现在每个组件都会有每个道具。 Like in this case my HomePage component doesn't need the storeName prop but it still has it.就像在这种情况下,我的 HomePage 组件不需要storeName道具,但它仍然有它。 Once I start adding other components which need other state variables, maybe this could cause a lot of variables to be stored in memory?一旦我开始添加需要其他状态变量的其他组件,也许这会导致很多变量存储在内存中? It doesn't seem ideal.似乎并不理想。


Update #2更新 #2

It's possible I'm going in the wrong direction by using route configs.通过使用路由配置,我可能走错了方向。 Seems like that is actually opposite to react router's philosophy as I understand it from here https://reacttraining.com/react-router/web/guides/philosophy .似乎这实际上与反应路由器的哲学相反,因为我从这里理解它https://reacttraining.com/react-router/web/guides/philosophy Maybe I'll stick with my first implementation w/o the route config, but it'd still be nice to know how using the route config and passing in the correct props can be achievable.也许我会坚持我的第一个没有路由配置的实现,但是知道如何使用路由配置和传递正确的道具是可以实现的仍然很好。

In your Update #1 just extract the props you want在您的更新 #1 中,只需提取您想要的道具

const routeConfig = [
    {
        path: '/',
        exact: true,
        component: () => <HomePage />,
    },
    {
        path: '/category',
        exact: false,
        component: ({storeName}) => {
            return <CategoryPage storeName={storeName} />
        },
    },
]

Or you could use a list of relevant props for each component and extract them on the go或者您可以为每个组件使用相关道具列表并随时随地提取它们

function pickProps(availableProps = {}, selection = []) {
  return selection.reduce(
    (props, selectedProperty) => {
      props[selectedProperty] = availableProps[selectedProperty];
      return props;
    },
    {}
  );
}

// ...

const routeConfig = [{
    path: '/',
    exact: true,
    component: HomePage,
  },
  {
    path: '/category',
    exact: false,
    component: CategoryPage,
    props: ['storeName'],
  },
  // ...
]

// ...
const componentProps = {storeName}
//....
<Switch>
    {routeConfig.map((route, i) => {
        return (
            <Route
                path={route.path}
                exact={route.exact}
                key={i}
            >
                <route.component
                   {...pickProps(componentProps, route.props)}
                />
            </Route>
        )
    })}
</Switch>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM