使用 Fragment 后,重定向在 Switch 内不起作用

Jam*_*rov 4 javascript reactjs react-router

版本

"react-router": "5.0.1",

测试用例

<Switch>
    <Route
        component={TestComponent}
        key={TestComponentPath}
        path={TestComponentPath}
        exact
    />
    {
        exampleCondition && (
            <>
                 <Route
                    component={TestComponent2}
                    key={TestComponentPath2}
                    path={TestComponentPath2}
                    exact
                 />
                 <Route
                    component={TestComponent3}
                    key={TestComponentPath3}
                    path={TestComponentPath3}
                    exact
                 />
            </>
        )
    }
    <Redirect to={redirectUrl} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

重现步骤

显示示例SwitchRedirect用例。

预期行为

redirectUrl如果没有匹配的路径,应该重定向到给定的路径。

实际行为

其行为就像Redirect在 switch 末尾没有提供 no 一样。问题可能是由于React.Fragment里面已经使用过造成的Switch。删除后重定向工作正常。

沙箱示例

https://codesandbox.io/s/react-router-tklng

Rik*_*kin 6

a 的所有子元素都<Switch>应该是<Route>or<Redirect>元素。仅渲染与当前位置匹配的第一个子项。

https://reacttraining.com/react-router/web/api/Switch/children-node

因为您正在使用 Fragment,所以您添加了不受支持的额外子项,Switch因此您的代码不会呈现。

您应该如下切换代码,添加条件路由而不使用片段:

<Switch>
    <Route
        component={TestComponent}
        key={TestComponentPath}
        path={TestComponentPath}
        exact
    />
    { exampleCondition &&
                 <Route
                    component={TestComponent2}
                    key={TestComponentPath2}
                    path={TestComponentPath2}
                    exact
                 /> }
    { exampleCondition &&
                  <Route
                    component={TestComponent3}
                    key={TestComponentPath3}
                    path={TestComponentPath3}
                    exact
                 /> }
    <Redirect to={redirectUrl} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

如果您担心重复代码,您可以在您的代码中添加额外的层,Route如下所示:

<Switch>
    <Route
        component={TestComponent}
        key={TestComponentPath}
        path={TestComponentPath}
        exact
    />
   {someCondition && [
            <Route
              component={TestComponent2}
              key={TestComponentPath2}
              path={TestComponentPath2}
              exact
            />,
            <Route
              component={TestComponent3}
              key={TestComponentPath3}
              path={TestComponentPath3}
              exact
            />
    ]}
    <Redirect to={redirectUrl} />
</Switch>
Run Code Online (Sandbox Code Playgroud)