【发布时间】:2019-05-21 12:36:05
【问题描述】:
我通过 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是仅在方法 componentWillReceiveProps 中可用
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>)
}
【问题讨论】:
标签: reactjs url react-redux react-router