React-router:更改查询字符串不会重新安装组件

React-router: changing query string does not re-mount the component

所以我有一个在 componentDidMount() 上获取数据的 React 组件。该组件路由可能采用查询字符串来确定要加载的资源(即资源的 id,/some/where?resource=123

当我更改查询字符串中的 id 并在浏览器中按 ENTER 时,组件没有重新挂载,而是保持原样。因此,不会加载资源 654 的数据。

为了解决这个问题,我可以将 componentDidMount 的代码复制并粘贴到 componentDidUpdate() 中,如果查询字符串发生变化,我会再次获取数据。

代码示例

  componentDidMount() {
    const { resource } = this.props.location.query;

    if (resource) {
      this.fetchData(); 
      // where fetch data is a function that makes calls
      // to an API and updates the Redux state
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { resource } = this.props.location.query;

    if (resource && resource !== prevProps.location.query.resource) {
      this.fetchData();
    }
  }

But is there a better way to handle this?

React router 从他们的文档中建议了这件事:Component Lifecycle

如果靠近底部,可以看到组件的数据获取示例。

我个人非常喜欢这种方式获取数据。它使数据获取与 React 生命周期相关联,因此您始终可以确定数据获取何时发生。