父更新会导致上下文消费者重新安装吗? [英] Parent update causes remount of context consumer?
问题描述
我有一个包装器组件,它创建一个上下文使用者并将上下文值作为道具传递给处理程序组件.当包装器组件的父级更新时,它会导致我的处理程序组件重新安装,而不仅仅是更新.
I have a wrapper component that creates a context consumer and passes the context value as a prop to a handler component. When the parent of the wrapper component updates, it's causing my handler component to remount instead of just update.
const Wrapper = forwardRef((props, ref) => {
class ContextHandler extends Component {
componentDidMount() {
// handle the context as a side effect
}
render() {
const { data, children } = this.props;
return (
<div ref={ref} {...data}>{children}</div>
);
}
}
return (
<Context.Consumer>
{
context => (
<ContextHandler
data={props}
context={context}
>
{props.children}
</ContextHandler>
)
}
</Context.Consumer>
);
});
我将包装器放在父组件中:
I put the wrapper inside a parent component:
class Parent extends Component {
state = {
toggle: false
}
updateMe = () => {
this.setState(({toggle}) => ({toggle: !toggle}))
}
render() {
const { children, data } = this.props;
return (
<Wrapper
onClick={this.updateMe}
{...data}
ref={me => this.node = me}
>
{children}
</Wrapper>
)
}
}
当我单击 Wrapper
并导致 Parent
中的更新时,ContextHandler
组件会重新安装,这会导致其状态重置.它应该只是更新/协调和维护状态.
When I click on the Wrapper
and cause an update in Parent
, the ContextHandler
component remounts, which causes its state to reset. It should just update/reconcile and maintain state.
我在这里做错了什么?
推荐答案
您的 ContextHandler
类是在 Wrapper 组件的渲染函数中实现的,这意味着将在每次渲染时创建一个全新的实例.要解决您的问题,请从 Wrapper
的渲染函数中提取 ContextHandler
的实现.
Your ContextHandler
class is implemented within the render function of the Wrapper component which means that an entirely new instance will be created on each render. To fix your issue, pull the implementation of ContextHandler
out of the render function for Wrapper
.
这篇关于父更新会导致上下文消费者重新安装吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!