首页 > 解决方案 > 反应获取 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>)
    }

标签: reactjsurlreact-reduxreact-router

解决方案


仅在 ID 更改时重新加载用户:

if (nextProps.match.params.id !== this.props.match.params.id) {
    this.props.getUserById(nextProps.props.match.params.id);
}

推荐阅读