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

IT技术 javascript reactjs react-router components
2021-05-10 14:23:55

我的 React 应用程序中有一个组件,它是一个表单。该表单用于创建新许可证或编辑现有许可证。无论哪种方式,它都只是一个组件,它会检查 componentDidMount() 是哪个“pageType”(添加/更新)。现在我的问题是,当我使用表单编辑许可证 (licensee/:id/edit) 并单击坐浴盆按钮以创建新许可证 (licensee/add) 时,它不会重新安装零件。它将更改 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}
            }}/>
        )
    }
  />
);

零件:

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'});
...
}}

编辑

这是它现在的工作方式:

          <PrivateRoute exact path="/licensees/add" key="add" component={this.LicenseeForm}/>
      <PrivateRoute exact path="/licensees/:Id/update" key="update" component={this.LicenseeForm}/>
3个回答

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

当路线相同并且只有路径变量发生变化时,在您的情况下是“id”,则路线顶层的组件会收到 componentWillReceiveProps 中的变化。

componentWillReceiveProps(nextProps) {
  // In this case cdm is not called and only cwrp know
  // that id has been changed so we have to updated our page as well
  const newLicenseId = nextProps.match.params.id;

  // Check id changed or not
  if(currentLicenseId != newLicenseId) {
    updateState(); // update state or reset state to initial state
  }
}

我正在粘贴代码,使您能够检测到该页面已更改并更新状态或将其重新分配为初始状态。另外,假设您第一次进入许可页面,然后将当前 Id 保存在一个变量中。只有您将在 componentWillReceiveProps 中使用来检测更改。

使用props“渲染”代替组件。

根据 Doc 组件props在父状态更改但渲染props更新时重新安装。

https://reacttraining.com/react-router/web/api/Route/route-render-methods