javascript - React Router V5 在路由中使用上下文变量的最佳方式

标签 javascript reactjs react-router react-router-dom

在我的应用程序中,我定义了路线,如下所示:

        <BrowserRouter>
          <Header />
          <div className="App">
            <Switch>
              <Route exact path="/">
                <Redirect to="/home" />
              </Route>
              <Route exact path={["/home", "/"]} component={Home} />
              <Route path="/account/:id" render={(props: RouteComponentProps<any>) => <Account {...props} />} />
              <Route component={NotFound} />
            </Switch>
          </div>
        </BrowserRouter>

我想知道的是,这可能很棘手,如果我希望我的路线有一个来 self 的上下文的前缀,即变量,我该怎么做,但问题是变量来自 api 响应?

如果我想要路由 /contextVariable/homecontextVariable 来自 api 响应并存储在上下文值中,我知道如何实现它变量到组件中,但路由如何处理它,即不成为 /undefined/home ,因为响应需要在插入路由之前完成?

有什么想法吗?

最佳答案

我曾经做过一个有类似需求的项目。在这种情况下,我没有声明动态路由,而是从状态中获取了一个路由数组,该数组是一个包含组件、路径和一些其他参数的对象数组。默认情况下,我添加了初始登陆页面,但未找到页面:

const [routes, setRoutes] = React.useState([
{
 component: HomeComponent,
 path: '/',
},
{
 component: NoMatchPage,
 path: '*',
}
])

然后我在 useEffect block 中收到请求,该请求将像这样更新此状态:

React.useEffect(()=>{
 // call api()
 const oldRoutes = routes;
 const noMatchPage = oldRoutes.pop();
 const newRoutes = [...oldRoutes, 
    responseFromApi.map(
     routeItem => 
        ({
          component: ComponentName, 
          path: routeItem.path
        })
     ), noMatchPage]
 setRoutes(newRoutes)
},[])

编辑1:因为我很健忘

抱歉,我忘记了主要部分,以下是路线渲染的方式:

<Switch>
    {
      routes.map(routeItem =>
        <Route path={routeItem.path} component={routeItem.component} />
      )
    }
</Switch>

此外,如果您想避免 useEffect 中的额外代码,您可以简单地执行以下操作:

React.useEffect(()=>{
 // call api()
 setRoutes(responseFromApi.map(
     routeItem => 
        ({
          component: ComponentName, 
          path: routeItem.path
        })
     ))
},[])

然后

<Switch>
    <Route exact path={["/home", "/"]} component={Home} />
    {
      routes.map(routeItem =>
        <Route path={routeItem.path} component={routeItem.component} />
      )
    }
    <Route component={NotFound} />
</Switch>

编辑2:因为我无知

如果用户直接输入 URL,而 Switch 无法识别 Route 并因此加载 NotFoundPage,您可以执行以下操作:

  1. useEffect block 内开始加载路径时设置一个条件:
const [loading, setLoading] = React.useState(false);
React.useEffect(() =>
    {
      setLoading(true);
      // load paths
      setLoading(false);
    }, [])
  • 在获取过程中,向用户显示 Loader:
  • return
        (
        <>
            {
               loading ? 
                 <LoaderComponent /> : 
                 <Switch>
                    // same as before
                 </Switch>
            }
        </>
        )
    

    最好显示一些内容供用户阅读,这样他们就不会生气,因为耐心已经成为过去。希望这有帮助!

    关于javascript - React Router V5 在路由中使用上下文变量的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73221783/

    相关文章:

    javascript - css 菜单或脚本在 ie 上不起作用

    javascript - 如何在 Javascript 中将十进制数转换为字符串?

    reactjs - React Router 4 阻止 iframe url

    javascript - 使用 React.js 时未定义 Web Speech API SpeechRecognition

    javascript - 如何使用 Prop 或状态在点击时渲染或不渲染这 5 种形式中的 1 种?

    reactjs - 如何在没有Link的情况下触发react-router

    reactjs - React TypeError : __WEBPACK_IMPORTED_MODULE_0_react__. PropTypes 未定义

    javascript - 根据 TypeScript 中的条件将数据从一个数组推送到另一个数组

    javascript - 在 React 中获取 firestore 引用字段的 uid

    javascript - Redux-form:在模式弹出时如何从 API 调用加载值(编辑模式)到表单?