【问题标题】:react rendering nested child routes when specifying only parent仅指定父级时反应渲染嵌套的子路由
【发布时间】:2020-12-22 14:25:02
【问题描述】:

我有一个包含这条路线的父容器

const App = () => {
    return ( <
        ProtectedRoute exact path = {
            `/parent`
        }
        redirectTo = "/welcome"
        component = {
            ParentComp
        }
        />
    )
}

在父 Comp 中:

const ParentComp = (props) => ( <>
  <StaticStuff/>
  <ProtectedRoute exact path = {`/:id`}
        redirectTo = "/welcome"
        component = {
            childComponent
        } 
</>)

然后在父组件中,我在子路径中渲染一个静态文本和一个子组件

当我在&lt;StaticStuff&gt; 内触发Parent route 路由时,我还看到了子组件的内容。但我想做的只是显示StaticStuffcomponent 然后在触发/parent/DynamicParam 时会在Static Stuff 下看到它。

这是Protected Route 的内容

const ProtectedRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => {
        return isAuthorized() ? <Component {...rest} {...props} /> :
            <Redirect to={{
                pathname: props.redirectTo,
                state: {
                    from: props.location
                }
            }} />
    }
    }>
    </Route>)

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    所以当路由等于/parent 时,会显示您的ParentComp。现在您在父组件中有一个带有参数 (/:id) 的路由,这显然也是由带有 id=parent 的路由 /parent 触发的。

    所以要么在 ParentComp 中嵌套路由(例如/parent/:id),要么使用查询参数有条件地显示子组件。

    【讨论】:

    • 你的意思是我真的这样做了吗?我在 Parent 中嵌套子路由
    • 不,只有嵌套Route Components不会自动嵌套路径。您需要在路由中包含现有的匹配路径/parent。在此处查看示例stackoverflow.com/a/43311025/10696402
    猜你喜欢
    • 2019-01-12
    • 2018-06-27
    • 2021-10-23
    • 2016-08-11
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多