在反应渲染中重用组件实例
父类有几个子组件,所有的子都是在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
"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;
根据^^这段代码,我认为你要么渲染EmptyComponent
或GpSearch
组件。所以无论何时placeHolderValue
更改您卸载当前重新渲染的组件。这就是你的组件每次都被重新实例化,因此你失去了子组件的内部状态。
另一种方法是,您将孩子的状态保存在父母(作为父母组件的状态)中,并根据需要将其作为道具传递给孩子。