路由参数更改时组件不会重新安装 [英] Component does not remount when route parameters change

查看:24
本文介绍了路由参数更改时组件不会重新安装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-router 开发一个 React 应用程序.我有一个项目页面,其网址如下:

I'm working on a react application using react-router. I have a project page that has a url as follows:

myapplication.com/project/unique-project-id

当项目组件加载时,我从 componentDidMount 事件触发该项目的数据请求.我现在遇到了一个问题,如果我直接在两个项目之间切换,那么只有 id 像这样更改...

When the project component loads, I trigger a data request for that project from the componentDidMount event. I'm now running into an issue where if I switch directly between two projects so only the id changes like this...

myapplication.com/project/982378632
myapplication.com/project/782387223
myapplication.com/project/198731289

componentDidMount 不会再次触发,因此不会刷新数据.是否应该使用另一个生命周期事件来触发我的数据请求或解决此问题的不同策略?

componentDidMount is not triggered again so the data is not refreshed. Is there another lifecycle event I should be using to trigger my data request or a different strategy to tackle this issue?

推荐答案

如果链接指向同一个路由,只是参数不同,它不会重新挂载,而是接收新的 props.因此,您可以使用 componentWillReceiveProps(newProps) 函数并查找 newProps.params.projectId.

If the link is directing to the same route with just a different param, it's not remounting, but instead receiving new props. So, you could use the componentWillReceiveProps(newProps) function and look for newProps.params.projectId.

如果您尝试加载数据,我建议您在路由器使用组件上的静态方法处理匹配之前获取数据.看看这个例子.React 路由器超级演示.这样,组件将加载数据并在路由参数更改时自动更新,而无需依赖 componentWillReceiveProps.

If you're trying to load data, I would recommend fetching the data on before the router handles the match using static methods on the component. Check out this example. React Router Mega Demo. That way, the component would load the data and automatically update when the route params change without needing to rely on componentWillReceiveProps.

这篇关于路由参数更改时组件不会重新安装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆