加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:44:17 所属栏目:百科 来源:网络整理
导读:所以我有一个React组件,它在componentDidMount()上获取数据.该组件路由可以采用查询字符串来确定要加载哪个资源(即资源的id,/ some / where?resource = 123. 当我更改查询字符串中的id并在浏览器中按Enter时,组件不会重新装入,而是保持不变.因此,没有加载资
所以我有一个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();
    }
  }

But is there a better way to handle this?

React路由器从他们的文档中建议了这一点: Component Lifecycle

如果您仔细观察底部,可以获取组件的数据获取示例.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读