2017-07-31 58 views
0

Parent Component收到的數據可用於Child Componentrender()方法中,但很明顯,無法在render方法中設置狀態,因爲它會創建無限循環。來自父母道具收到的數據如何setState()?我可能錯過了一些東西,但我也嘗試了所有的生命週期組件,但沒有取得太大的成功。如何從作爲來自父組件的道具收到的數據中設置當前組件狀態?

例如,

import React from 'react'; 

class Parent extends React.Component 
{ 
    render() 
    { 
    let user = {name: John, age: 28}; 
    return(
     <Child user={user}> 
    ); 
    } 
} 

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

    render() 
    { 
    const user = this.props.user; 
    console.log(user); // --> [✓] Outputs {name: John, age: 28}; 
    // this.setState({ user }) // --> [✘] 

    return(
     <div></div> 
    ); 
    } 
} 

我該怎麼辦呢?

回答

1

使用componentWillReceiveProps

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

    componentWillReceiveProps(nextProps){ 
    if(this.state.user != nextProps.user){ 
     this.setState({ user:nextProps.user }); 
    } 
    } 
    render() 
    { 
    const user = this.props.user; 
    console.log(user); // --> [✓] Outputs {name: John, age: 28}; 
    // this.setState({ user }) // --> [✘] 

    return(
     <div></div> 
    ); 
    } 
} 
+0

這是完美的解釋,謝謝你,Dhamecha! – anonym

+0

感謝兄弟...請接受我的回答.. –

+0

請稍等3分鐘:) – anonym

1

您需要使用componentWillReceiveProps()生命週期方法,只要道具值發生任何變化,它就會被調用。

componentWillReceiveProps()

componentWillReceiveProps()一個安裝部件 接收新道具之前被調用。如果您需要更新狀態以響應prop更改(例如,重置它),您可以比較this.props 和nextProps,並使用this.setState()以 此方法執行狀態轉換。

componentWillReceiveProps(newProps){ 
    /*compare new values and previous value first if they are not same then update the state*/ 
    if(condition) 
     this.setState({users: newProps.users}) 
} 
+0

這是正確的。非常感謝。 – anonym

相關問題