【问题标题】:(React) Render only one child (from props.children) depends of route (location.pathname)(反应)只渲染一个孩子(来自props.children)取决于路线(location.pathname)
【发布时间】:2019-02-19 16:34:04
【问题描述】:

这是我的Switch:

<Switch>
    <Main>
      <Route exact path="/login" component={LoginForm} />
      <Route exact path="/register" component={RegisterForm} />
    </Main>
</Switch>

Main 组件 - 是子组件的包装器:

class Main extends Component {
     render() {
        const { children } = this.props;

        return (
            ...
            {children}
            ...
        )
     }
}

这会将我的所有(子)组件返回为LoginFormRegisterForm

所以我只需要获取一个依赖于路线的组件 (props.location.pathname)

在这种情况下,正确的解决方案是什么?

【问题讨论】:

    标签: reactjs routing routes children


    【解决方案1】:

    似乎您还需要为第一个路由标签添加“精确”。它将解决问题。因为 '/' 将匹配所有路由。因此,为了使其具体化,您还需要为第一条路线提供确切的信息。

    【讨论】:

    • 那么现在您还面临这个问题吗?我想现在当你有'/'或'login'作为路径名时,它会显示LoginForm,当你有'/register'时,它会显示我认为是预期的RegisterForm。这还没有发生吗?
    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多