React-Router不会在不同路径上重新安装组件

Xxt*_*eem 1 javascript components reactjs react-router

我的应用程序中有一个组件是一种形式。该表格用于创建新许可证或编辑现有许可证。无论哪种方式,它都是一个组件,并检查componentDidMount()是哪个“ pageType”(添加/更新)。现在我要解决的问题是,当我使用表单来编辑许可证(被许可人/:id /编辑),并且单击作为坐浴盆的按钮来创建新许可证(被许可人/添加)时,它不会重新安装零件。它将更改URL,但所有预加载的数据仍处于表单中。

  LicenseeForm = Loadable({
    loader: () => import('./license/LicenseeForm'),
    loading: 'Loading..'
  });

render() {
    return (
      <Router>
        <Switch>
          <LoginRoute exact path="/" component={this.LoginView}/>
          <LoginRoute exact path="/login" component={this.LoginView}/>
          <PrivateRoute exact path="/licensees/add" component={this.LicenseeForm}/>
          <PrivateRoute exact path="/licensees/:id/update" component={this.LicenseeForm}/>
          <Route path="*" component={this.NotFoundPage}/>
        </Switch>
      </Router>
    )
  }

const PrivateRoute = ({component: Component, ...rest}) => (
  <Route
    {...rest}
    render={props =>
      authService.checkIfAuthenticated() ? (<Component {...props} />) :
        (<Redirect
            to={{
              pathname: "/login",
              state: {from: props.location}
            }}/>
        )
    }
  />
);
Run Code Online (Sandbox Code Playgroud)

零件:

componentDidMount() {
    const locationParts = this.props.location.pathname.split('/');
    if (locationParts[locationParts.length-1] === 'add') {
      this.setState({pageType: 'add'});
    } else if (locationParts[locationParts.length-1] === 'update') {
      this.setState({pageType: 'update'});
...
}}
Run Code Online (Sandbox Code Playgroud)

编辑

现在是这样的:

          <PrivateRoute exact path="/licensees/add" key="add" component={this.LicenseeForm}/>
      <PrivateRoute exact path="/licensees/:Id/update" key="update" component={this.LicenseeForm}/>
Run Code Online (Sandbox Code Playgroud)

Piy*_*ani 5

如果在更改路线时确实需要重新安装组件,则可以将唯一键传递给组件的key属性(该键与您的路径/路由相关联)。因此,每次路线更改时,密钥也会更改,从而触发React组件卸载/重新安装。