父更新导致重新安装上下文消费者?

Parent update causes remount of context consumer?

我有一个包装器组件,它创建一个上下文使用者并将上下文值作为 prop 传递给处理程序组件。当包装器组件的父组件更新时,它会导致我的处理程序组件重新挂载,而不仅仅是更新。

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>
  );
});

我将包装器放在父组件中:

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 组件重新安装,这导致其状态重置。它应该只是 update/reconcile 并保持状态。

我做错了什么?

您的 ContextHandler class 是在 Wrapper 组件的渲染函数中实现的,这意味着将在每次渲染时创建一个全新的实例。要解决您的问题,请将 ContextHandler 的实现从 Wrapper.

的渲染函数中拉出