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

nbk*_*ope 9 lifecycle fetch reactjs

所以我有一个React组件来获取数据componentDidMount().该组件路由可以采用查询字符串来确定要加载哪个资源(即资源的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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

但有没有更好的方法来处理这个?

B R*_*Rob 6

React 路由器从他们的文档中提出了这个确切的建议:组件生命周期

如果您仔细观察底部,则有一个为组件获取数据的示例。

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