我需要创建一个仅适用于某些管线的布局.然而,当我使用交换机并分离需要备用布局的路由时,如果我try 访问一个不存在的页面,它只会将我带到其中没有任何内容的布局.下面是示例代码.

<Switch>
    <Route exact path="/" component={SampleComponent} />
    <TokenLayout>
        <Route path="/some-random-component" component={SomeRandomComponent} />
    </TokenLayout>
    <Route path="*" component={NotFound} />
</Switch>

NotFound组件从不渲染,而是渲染没有子级的TokenLayout.

对如何解决这个问题有什么建议吗?

推荐答案

Issue

这里的问题是Switch组件"呈现与位置匹配的第一个子级<Route><Redirect>"官方文件没有明确指出Route(and variations of)和RedirectSwitch组件中唯一有效的子组件.当命中非路由或非重定向组件时,路由匹配停止,that组件返回并呈现.接下来发生的是,嵌套路由渲染SomeRandomComponent被包括性地匹配,就像它将由路由而不是在Switch内一样.

Solution

重构代码,使TokenLayout组件inside呈现路径.

以下是一些建议:

  • 创建包装器组件

      const TokenLayoutWrapper = props => (
        <TokenLayout>
          <SomeRandomComponent {...props} />
        </TokenLayout>
      );
    

    ...

      <Switch>
        <Route exact path="/" component={SampleComponent} />
        <Route path="/some-random-component" component={TokenLayoutWrapper} />
        <Route path="*" component={NotFound} />
      </Switch>
    
  • 创建高阶组件

      const withTokenLayout = Component => props => (
        <TokenLayout>
          <Component {...props} />
        </TokenLayout>
      );
    

    装饰SomeRandomComponent组件导出:

      export default withTokenLayout(SomeRandomComponent);
    

    ...

      <Switch>
        <Route exact path="/" component={SampleComponent} />
        <Route path="/some-random-component" component={SomeRandomComponent} />
        <Route path="*" component={NotFound} />
      </Switch>
    
  • 只需使用renderprops 在内联函数中包装SomeRandomComponent,将路由props 传递到SomeRandomComponent.

      <Switch>
        <Route exact path="/" component={SampleComponent} />
        <Route
          path="/some-random-component"
          render={props => (
            <TokenLayout>
              <SomeRandomComponent {...props} />
            </TokenLayout>
          )}
        />
        <Route path="*" component={NotFound} />
      </Switch>
    

Reactjs相关问答推荐

条件索引路由

Next.js-图像组件加载问题

通过单击具有此值的按钮将值添加到数组对象键

更改购物车中的产品数量后,PayPal Reaction/Next JS按钮未更新

获取点击的国家/地区名称react 映射

在React Create App TS项目中安装material UI

在url中使用MongoDB对象ID被认为是不好的做法?

为什么查询错误在处理后仍出现在控制台中?RTK查询+ React

React useEffect 问题...异步函数内的变量正在获取延迟的更新值

如何在React组件中自动更新图表数据?

在 React 中使用forwardRef时无法声明自定义属性

在一个事件处理程序中进行多次调度是个好主意吗?

提前输入错误:选项类型上不存在属性名称

如何将 DocuSign 控制台界面嵌入到 React 应用中

Material UI @mui/material/Button vs @material-ui/core/Button,它什么时候改变的,旧版本的文档在哪里

Recharts 笛卡尔网格 - 垂直线和水平线的不同样式

React Native Realm 应用程序在发布构建后崩溃

setState 改变对象引用

gtag:为什么谷歌分析即使没有被授权也会收集数据

在 Redux 中更新布尔状态时出错