【问题标题】:React router always renders first route in nested componentReact 路由器总是在嵌套组件中渲染第一个路由
【发布时间】:2019-06-21 11:18:49
【问题描述】:

在 react-router 渲染的组件中,我有另一个路由。但是,从这些嵌套路由中,无论实际路径如何,始终只渲染第一条路由。 我阅读了有关更新阻塞的信息并尝试将组件包装到 withRouter() 中,但没有帮助。

我阅读了有关更新阻塞的信息,并尝试将组件包装到 withRouter() 中,但没有帮助。 重新排序路线会产生相同的行为。

App.js

class App extends Component{
    render() {
        return (
            <div>
                <Router>
                    <Switch>
                        <Route path="/login" component={Login} />
                        <PrivateRoute path="/" component={Main}  />
                    </Switch>
                </Router>
                <Modal />
            </div>
        )
    }
}

Main.js

class Main extends Component{
    render(){
        return (
            <div className="full-height flex-container flex-column">

                <div style={{display: "flex", flexDirection: "row", height: "100%"}}>
                    <NavigationBar items={[{name: 'Categories', route: '/'}, {name: 'Products', route: '/products'}]} />
                    <Content />
                </div>
            </div>
        )
    }
}

Content.js 和有问题的路由本身

class Content extends Component{
    render(){
        return(
            <div style={{ width: "100%"}}>
               <Switch>
                    <Route exact to="/" component={CategoriesPage} />
                    <Route to="/products" component={ProductsPage} />
               </Switch>
            </div>
        )
    }
}

我希望路径“/” - 呈现类别页面,以及“/products” - ProductsPage,但现在为“/”和“/products”呈现类别页面。 提前致谢。 此处提供示例:https://codesandbox.io/s/github/nomernabis/login-flow-redux

【问题讨论】:

  • 你是如何导航的?,通过链接或通过 URL。网址有变化吗?
  • 是的 url 正在改变。我尝试浏览两个链接,触发 this.props.history.push(),并直接输入浏览器 url。行为是一样的。
  • 尝试&lt;Route component={Content} /&gt; 而不是&lt;Content /&gt; 看看它是否有任何改变。除此之外,您的代码对我来说还不错
  • 我试过了,还是一样。
  • 在您的 Content 类中,替换 to,改用 path。它解决了你的问题吗?

标签: reactjs react-router


【解决方案1】:

你正在传递你的路线 to 而不是 Content.js 中的 path

这里的工作实现:https://codesandbox.io/s/mm10x7150p

    <Switch>
      <Route exact path="/" component={CategoriesPage} />
      <Route exact path="/products" component={ProductsPage} />
    </Switch>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2017-06-07
    • 2017-11-15
    • 2019-01-12
    • 2019-03-02
    相关资源
    最近更新 更多