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

后端 未结 4 1707
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 19:19

I am trying to have separate routes but same component for add/edit forms in my react app like the below:


        

        
相关标签:
4条回答
  • 2020-12-29 19:51

    One solution is use inline function with component, that will render a new component each time, But this is not a good idea.

    Like this:

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

    Better solution would be, use componentWillReceiveProps lifecycle method in ManageClient component. Idea is whenever we render same component for two routes and switching between them, then react will not unmount-mount component, it will basically update the component only. So if you are making any api call or require some data do all in this method on route change.

    To check, use this code and see it will get called on route change.

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

    Note: Put the condition and make the api call only when route changes.

    0 讨论(0)
  • 2020-12-29 19:52
    <Route exact path={["/add-client", "/edit-client"]}>
      <manageClient />
    </Route>
    

    Reference

    Version 5.2.0

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

    0 讨论(0)
  • 2020-12-29 20:03

    Using different key for each route should force components to rebuild:

        <Route 
          key="add-client"
          exact path="/add-client"
          component={manageClient} 
        />
    
        <Route 
          key="edit-client"
          exact path="/edit-client"
          component={manageClient} 
        />
    
    0 讨论(0)
  • 2020-12-29 20:16

    My problem was we used an common path in-between, which causes dynamic path to not working

          <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);
    .............    
    
    0 讨论(0)
提交回复
热议问题