如何使用 React Router 获取两个组件的异或路由?

How to get XOR-routing of two components with React Router?

我的应用程序 - 组件看起来像这样:

class App extends Component {
    render() {
        return (
            <div>
                <Route path='/:category?/:post?' component={Posts}/>
                <Route exact path='/edit' component={PostForm}/>
            </div>
        )
    }
}

现在的问题是,我想要 XOR 行为,即当呈现第一个组件时,我不希望呈现第二个组件,反之亦然。我实际得到的是 URL 像 localhost3000/books/123344 只有第一个组件被渲染,但是 URL localhost3000/create ,两个组件都被渲染。

这是什么原因,我怎样才能得到两个组件的所需 XOR 渲染?

使用react-router switch,只会渲染一个组件。同时切换路由的顺序。

试试这个:

<Switch>
    <Route exact path='/edit' component={PostForm}/>
    <Route path='/:category?/:post?' component={Posts}/>
</Switch>