父類有幾個子組件,所有的子都是在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