【问题标题】:React-router doesn't remount component on different pathsReact-router 不会在不同的路径上重新安装组件
【发布时间】:2023-04-11 04:46:01
【问题描述】:

我的反应应用程序中有一个组件,它是一个表单。该表格用于创建新许可证或编辑现有许可证。无论哪种方式,它都只是一个组件,它会检查 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}/>

【问题讨论】:

标签: javascript reactjs react-router components


【解决方案1】:

使用 props 'render' 代替组件。

根据文档组件道具重新安装,而父状态更改但渲染道具更新。

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

【讨论】:

    【解决方案2】:

    当路由相同并且只有路径变量更改时,在您的情况下是“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 中使用来检测变化。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 非常感谢!我创建了父组件和子组件。获取父组件上的参数并将参数传递给子组件。
      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2018-08-06
      • 2018-05-25
      相关资源
      最近更新 更多