2017-02-15 192 views
6

我无法弄清楚如何在this.props.user的值更改时使我的组件重新渲染。最初,this.props.user的值为空,但在数秒后变为实际值。下面我显示了子组件。父组件将商店状态映射到它的道具,并将其传递给下面的子组件类。反应使用componentWillReceiveProps重新渲染组件

export class UserInfoComponent extends Component { 
    constructor(props){ 
    super(props); 
    this.state = {user: this.props.user} 
    } 

    componentWillReceiveProps(){ 
    this.setState({user: this.props.user}) 
    } 

    render() { 
    if(this.state.user) 
    return (
     <h1>{this.state.user.firstName}</h1> 
    ); 

    return (
     <h1>loading</h1> 
    ) 
    } 
} 

回答

18

componentWillReceiveProps接收nextProps作为参数。与你目前的代码,你只是设置用户回到当前的状态。您需要使用提供的nextProps参数。

export class UserInfoComponent extends Component { 
    constructor(props){ 
    super(props); 
    this.state = {user: this.props.user} 
    } 

    componentWillReceiveProps(nextProps){ 
    this.setState({user: nextProps.user}) 
    } 

    render() { 
    if(this.state.user) 
    return (
     <h1>{this.state.user.firstName}</h1> 
    ); 

    return (
     <h1>loading</h1> 
    ) 
    } 
} 
+0

为什么要使用状态?道具变化已经导致组件的重新渲染。 – FurkanO

+0

这里的主要区别在于,在提问者的例子中,他们将他们传递的道具转换为自己的内部状态。只有在组件被呈现在任何位置时才会发生这种情况,即我引用的'this.state.user'将始终引用自组件构建期间发生的第一个值。 'componentWillReceiveProps'更新父组件已经通过新道具时的状态,但这不会自然发生,为什么将道具转换成状态通常是反模式 – finalfreq

+0

我的观点是,你不必听道具变化重新渲染一个组件。提问者可能不知道这一点。我没有问过这个区别。 – FurkanO