2016-12-02 81 views
0

父類有幾個子組件,所有的子都是在render方法內部實例化的,所以任何對父狀態的改變都會導致所有的子實例都被重新實例化,每次渲染都被調用react創建新實例兒童,由失去孩子的狀態,以重用子實例我試圖使用檢索孩子parent.refs.childRef例如有,但是這給了我錯誤在反應渲染中重用組件實例

Uncaught Error: Objects are not valid as a React child

,這裏是我的代碼

placeHolderComponent(){ 
     let component; 
     let palceHolderValue=this.state.uiState.placeHolder; 
     let classInstance=this; 
     if(palceHolderValue=='empty'){ 
      component=<EmptyComponent></EmptyComponent> 
     } 
     else if(palceHolderValue=='search'){ 
       component= classInstance.refs.gpSearchComponent!=null? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/> 
     } 
     return component; 
    } 

此處GpSearch組件用ref屬性實例化,代碼檢查parent.refs.childComponentRefId是否爲null,然後渲染該實例,而不是新實例。我收到此錯誤

Uncaught Error: Objects are not valid as a React child (.... If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons

回答

1

"any change to parent state will cause all the children to be re instantiated"

沒有任何改變父狀態會引起家長和孩子的重新渲染。子組件是未重新創建,但重新呈現(儘管您可以避免使用生命週期鉤子shouldComponentUpdate重新渲染兒童)。

"loosing state of children"

再次號碼孩子在重新呈現時不會失去內部狀態。

的誤差大概是由該行拋出:

component = classInstance.refs.gpSearchComponent != null ? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/> 

因爲classInstance.refs.gpSearchComponent是一個對象,併爲投訴做出反應「未捕獲的錯誤:對象是不是一個陣營的孩子有效的」。

if(palceHolderValue=='empty'){ 
     component=<EmptyComponent></EmptyComponent> 
    } 
    else if(palceHolderValue=='search'){ 
      component= classInstance.refs.gpSearchComponent!=null? classInstance.refs.gpSearchComponent: <GpSearch ref="gpSearchComponent"/> 
    } 
    return component; 

根據^^這段代碼,我認爲你要麼渲染EmptyComponentGpSearch組件。所以無論何時placeHolderValue更改您卸載當前重新渲染的組件。這就是你的組件每次都被重新實例化,因此你失去了子組件的內部狀態。

另一種方法是,您將孩子的狀態保存在父母(作爲父母組件的狀態)中,並根據需要將其作爲道具傳遞給孩子。