在 react-router v4 中对不同的路由路径使用相同的组件

using same component for different route path in react-router v4

我正在尝试在我的 React 应用程序中为 add/edit 表单设置单独的路由但具有相同的组件,如下所示:

<Switch>
        <Route exact path="/dashboard" component={Dashboard}></Route>
        <Route exact path="/clients" component={Clients}></Route>
        <Route exact path="/add-client" component={manageClient}></Route>
        <Route exact path="/edit-client" component={manageClient}></Route>        
        <Route component={ NotFound } />        
</Switch>

现在在 manageClient 组件中,我解析查询参数(我在编辑路由中传入带有客户端 ID 的查询字符串),我根据传递的查询参数有条件地呈现。

问题是这不会再次重新安装整个组件。假设打开了一个编辑页面,并且用户单击了添加组件,URL 发生了变化,但组件没有重新加载,因此仍保留在编辑页面上。

有办法处理吗?

对每条路线使用不同的 key 应该强制组件重建:

    <Route 
      key="add-client"
      exact path="/add-client"
      component={manageClient} 
    />

    <Route 
      key="edit-client"
      exact path="/edit-client"
      component={manageClient} 
    />

一个解决方案是在组件中使用内联函数,每次都会渲染一个新组件,但这不是一个好主意。

像这样:

<Route exact path="/add-client" component={props => <ManageClient {...props} />}></Route>
<Route exact path="/edit-client" component={props => <ManageClient {...props} />}></Route> 

更好的解决方案是,在 ManageClient 组件中使用 componentWillReceiveProps 生命周期方法。想法是每当我们为两条路线渲染相同的组件并在它们之间切换时,react 不会 unmount-mount 组件,它基本上只会更新组件。因此,如果您正在进行任何 api 调用或需要一些数据,请在路由更改时在此方法中完成所有操作。

要检查,请使用此代码,看看它会在路线更改时被调用。

componentWillReceiveProps(nextProps){
   console.log('route chnaged')
}

注意:设置条件,仅在路由变化时才进行api调用。

<Route exact path={["/add-client", "/edit-client"]}>
  <manageClient />
</Route>

参考

版本 5.2.0

https://reacttraining.com/react-router/web/api/Route/path-string-string

我的问题是我们在中间使用了 common 路径,这导致动态路径无法正常工作

      <Switch>
        <Route key="Home" path="/home" component={Home} />
        <Route key="PolicyPlan-create"  path="/PolicyPlan/create" component={PolicyPlanCreatePage} />
        {/* <Route key="PolicyPlan-list" path="/PolicyPlan" component={PolicyPlanListPage} /> */}
        <Route key="PolicyPlan-list" path="/PolicyPlan/list" component={PolicyPlanListPage} />            
        <Route key="PolicyPlan-edit"  path="/PolicyPlan/edit/:id" component={PolicyPlanCreatePage} />   
        <Route key="cardDesign" path="/cardDesign" component={cardDesign} />
        <Route key="Admin-create" path="/admin/create" component={RegisterPage} />
      </Switch>

So don't use the path like the commented one, now the code is working

.................
          this.props.history.push("/PolicyPlan/edit/" + row.PolicyPlanId);
.............    

您可以简单地在单个路由标记中提供一组路径,如下所示 -

<Route exact path={["/add-client", "/edit-client"]} component={manageClient}></Route>