React Router 修改 URL 如果所有参数都没有传递

React Router modify URL if all params are not passed

我正在尝试解决我的应用程序中的一个问题,当用户未在 URL 中输入所有路由参数时,我需要修改 URL。 这是我的路由器的样子:

<Switch>
    <Route path="/A" exact strict component={T3} />
    <Route path="/B" exact strict component={BestOf} />
    <Route path="/C/:id" component={Author} />
    <Route path="/D" exact strict component={About} />
    <Route path="/E" exact strict component={ContactUs} />
    <Route path="/F/:id/:subId" exact strict component={Careers} />
    <Redirect to="/"
</Switch>

会发生什么:如果我在 URL 栏中输入 http://localhost:3000/F/1,应用会重定向到 /

我想要的:我想把这样的URL改成http://localhost:3000/F/1/0

我尝试在 Switch 中使用另一个 Switch 来处理这个问题,但我没有得到想要的结果。

如有任何帮助,我们将不胜感激。 提前致谢。

可以做的是使 url 参数可选,并在 Careers 组件中重定向到有效的默认值 url

<Switch>
    <Route path="/A" exact strict component={T3} />
    <Route path="/B" exact strict component={BestOf} />
    <Route path="/C/:id" component={Author} />
    <Route path="/D" exact strict component={About} />
    <Route path="/E" exact strict component={ContactUs} />
    <Route path="/F/:id?/:subId?" exact strict component={Careers} />
    <Redirect to="/" />
</Switch>

现在在 Careers 组件渲染方法中

render() {
     const { match: { params }} = this.props;
     if (!params.id || !params.subId ) {
        return <Redirect to=`${match.url}/0/0` />
     }
     // rest code here
}