父类有几个子组件,所有子组件都在render方法中实例化,因此对父级状态的任何更改都会导致所有子组件被重新实例化,每次调用render时都会创建子级的新实例,通过丢失子级状态,为了重用子实例,我尝试使用parent.refs.childRef检索子实例,但这给了我错误
未捕获错误:对象作为React子对象无效
,这是我的代码
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;
}
这里使用ref属性实例化GpSearch Component,并且代码检查parent.refs.childComponentRefId是否为null然后呈现该实例,而不是新实例 . 我收到了这个错误
未捕获错误:对象作为React子对象无效(....如果您要渲染子集合,请改为使用数组或使用React附加组件中的createFragment(object)包装对象
1 回答
不,对父状态的任何更改都可能导致重新呈现父级及其子级 . 子组件是 not recreated ,但 re-rendered (虽然您可以避免使用生命周期钩子
shouldComponentUpdate
重新渲染子项) .再一次 . 儿童在重新渲染时不会失去内部状态 .
该行可能会引发错误:
因为
classInstance.refs.gpSearchComponent
是一个对象而且React抱怨"Uncaught Error: Objects are not valid as a React child" .根据^^这段代码,我想你要么呈现一个
EmptyComponent
或GpSearch
组件 . 因此,每当placeHolderValue
更改时,您都会卸载当前重新渲染的组件 . 这就是每次重新实例化组件的方式,从而丢失子组件的内部状态 .另一种方法是,将子项的状态保存在父项中(作为父组件的状态),并根据需要将其作为道具传递给子项 .