Redux + React:react router 只渲染索引路由

Redux + React : react router only rendering index route

我尝试按照 上的答案进行操作,但无济于事。 我正在尝试使用反应路由器和嵌套路由来根据路由器的配置呈现不同的布局。 但是带有 path="/" 的路由总是显示,而不管 URL 是否存在。 这是我正在使用的路由器。

        <Route component={App}>
            <Route component={LayoutOne}>
                <Route path="/" component={ComponentOne}/>
            </Route>
            <Route component={LayoutTwo}>
                <Route path="category" component={ComponentTwo}/>
            </Route>
        </Route>

这是我用来将调度映射到道具并连接的应用程序文件。

function mapStateToProps(state, ownProps){
    return{
        exampleProp: state.exampleProp,
    };
}

function mapDispatchToProps(dispatch){
    return bindActionCreators(actionCreators, dispatch);
}


const App = connect(mapStateToProps, mapDispatchToProps)(MainLayout);

export default App;

这是主布局 MainLayout 如上所示。

export default class MainLayout extends Component {
    render(){
       <div className="main-layout">
            {this.props.children}
       </div>
    }
}

LayoutOne 和 LayoutTwo(为简洁起见已省略)是简单的 class 说唱歌手,如下所示。

导出默认 class LayoutOne 扩展组件{ 使成为(){ return( {this.props.children} ) } }

而这里的ComponentOne和ComponentTwo分别只是简单的组件。

我的问题是无论 URL 存在什么,只有 ComponentOne 会呈现。 我该如何解决这个问题,以便我可以使用如上所示的嵌套路由? 非常感谢您的帮助。 如果您需要任何其他信息,请询问,我会尽力使用所需信息更新问题。 谢谢。

您遇到的问题是索引路由,即 '/',首先在您的路由树中匹配,并且因为它匹配任何路由,所以每次都会呈现该路由。

您可以通过将带有 path="category"Route 移动到带有 path="/" 的上方来解决此问题。这样,首先检查更详细的路线选项。为了清楚起见,我还建议将 path="category" 更改为 path="/category",因为两者都是根级别路由。

将您的路线更改为这样应该可以解决您的问题

<Route component={App} path="/">
    <Route component={LayoutOne} path="">
        <Route component={ComponentOne}/>
    </Route>
    <Route component={LayoutTwo} path="category">
        <Route component={ComponentTwo}/>
    </Route>
</Route>