所以我有一个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
原文地址:https://www.jb51.cc/react/300826.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。