Reactjs 检测React中的URL参数更改
React未检测url中的最后一个参数何时更改。如果我重新加载页面,它就会工作 我正在使用“react router dom”:“^5.0.1” “路由器” 但是我得到了这个警告Reactjs 检测React中的URL参数更改,reactjs,Reactjs,React未检测url中的最后一个参数何时更改。如果我重新加载页面,它就会工作 我正在使用“react router dom”:“^5.0.1” “路由器” 但是我得到了这个警告 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. 反应挂钩或模具?当组件装入时,只调用一次ComponentDidMount。当您更改URL时,您的组件可能会由于react router而重新呈现,
Warning: componentWillReceiveProps has been renamed, and is not recommended for use.
反应挂钩或模具?当组件装入时,只调用一次ComponentDidMount。当您更改URL时,您的组件可能会由于react router而重新呈现,但该组件已装入,并且不会再次运行该代码
我认为在这种情况下,您可以直接在render方法中引用this.props.match.params.id,而不是将其设置为state。或者,您可以使用componentDidUpdate,同时检查哪些道具已更改以重置状态。
ComponentDidMount
只调用一次(当组件装载时),因此,如果更改路由无关紧要,则不会再次调用生命周期
为了实现您想要的,我建议您使用另一个生命周期,如(componentdiddupdate
或getDerivedStateFromProps
)或开始使用钩子。或者,如果简单,则直接在渲染方法中使用道具
更新:
这应该可以做到:
componentDidUpdate(prevProps) {
if (this.state.userId !== this.props.match.params.id) {
this.setState({ userId: this.props.match.params.id });
}
}
componentDidUpdate仍然可以安全使用,并在更新发生后立即调用
要检测URL或动态URL或URL查询参数的更改或在后退按钮上检测查询参数的更改,请使用componentDidUpdate
在
componentDidMount
中,似乎仅在装载时更改状态this.setState({'userId':id})
。单击链接不会重新安装用户组件。实际上,我正在使用this.state.userId调用服务以获取用户详细信息。我是否必须将这个类组件转换为函数组件才能使用钩子实现它?很抱歉,我还没有调查钩子。是的,为了使用钩子,必须将类组件转换为函数组件。您不必迁移到react钩子,在您的项目中,您可以混合使用具有生命周期方法的类组件和具有钩子的功能组件,这将起作用,但钩子使您的生活更轻松。使用钩子,您只关注效果(例如,当某些数据更改时,我应该做什么),而不是我应该使用什么生命周期。
componentWillReceiveProps(nextProps) {
const { id } = nextProps.match.params;
this.setState({'userId': id}
}
Warning: componentWillReceiveProps has been renamed, and is not recommended for use.
componentDidUpdate(prevProps) {
if (this.state.userId !== this.props.match.params.id) {
this.setState({ userId: this.props.match.params.id });
}
}
componentDidUpdate(prevProps) {
//to detect dynamic URL params according to above question
if (this.state.userId !== this.props.match.params.id) {
//your code here
}
//to detect URL query params update and backbutton
if (this.props.location.search !== prevProps.location.search) {
//your code here
}
}