reactjs - 反应获取 url 更改
问题描述
我通过 ID 获得用户个人资料。但是,当我尝试使用同一页面中的链接转到另一个用户的页面时,我无法从 URL 中获取新 ID。它被方法componentWillReceiveProps捕获,但我无法从中调用数据库请求来获取ID上的数据,因为发生了无限循环。
如何从 /profile/5cc6c0e743d02ff2860d8f20 链接获取新 ID,以便更新组件并从数据库中获取数据并将其插入到组件中?
实际上,我需要从 props.match.params.id 中获取 props 并将它们传递给 this.props.getUserById (this.props.match.params.id),而 props.match.params.id 仅在方法组件WillReceiveProps
class ProfileUser extends Component {
state = {
user: {}
};
componentDidMount() {
// When first time i load component it works fine, i call database and get info
this.props.getUserById(this.props.match.params.id);
}
componentWillReceiveProps(nextProps) {
// Here I get user information
this.setState({user: nextProps.profile.user})
// when I switch to another page with another ID this.props.match.params.id, this method works but I can't call this.props.getUserById(this.props.match.params.id); from here because an infinite loop appears
// this.props.getUserById(this.props.match.params.id);
}
render() {
console.log(this.state.user)
return (<div></div>)
}
解决方案
仅在 ID 更改时重新加载用户:
if (nextProps.match.params.id !== this.props.match.params.id) {
this.props.getUserById(nextProps.props.match.params.id);
}
推荐阅读
- tensorflow - TensorFlow 获取优化器计算的更新
- python - 从烧瓶网络服务器调用 c++ 库的 python 包装函数
- oracle - Oracle 中的日期操作
- algorithm - 降低排序算法中的大 O 复杂度
- sql - 全外连接不返回右表的结果
- java - 从 PCF 连接到 windows 服务器
- c# - Splat.Locator 一个 ViewModel 的多个视图
- r - 使用扫描从数据帧的每一行中减去一个向量
- powershell - 无法从 PScustomobject 转换为 Arraylist
- python-3.x - 如何检查字典中嵌套列表中的项目是否为浮点数?