Parent update causes remount of context consumer?

拜拜、爱过 提交于 2021-01-29 06:11:43

问题


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

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.

What am I doing wrong here?


回答1:


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.



来源:https://stackoverflow.com/questions/55483564/parent-update-causes-remount-of-context-consumer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!