2017-02-15 182 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