将 React 16.2 升级到 16.8 后,上下文消费者收到以前的值而不是当前值

After upgrading react 16.2 to 16.8, context consumers receive previous value instead of current

我一直在使用 React 16.2,上下文 api 按预期使用以下结构工作。

const MyContext = createContext(null);

class Provider extends Component {
  state = {
    id: 'A value I set'
  }

  onUpdate = (e) => {
    const { id } = e.dataset
    this.setState({ id });
  }

  render() {
    const { children } = this.props;
    const { id } = this.state;
    return(
      <MyContext.Provider value={id}>
        {children}
      </MyContext.Provider>
    )
  }
}

function ConsumerHOC(WrappedComponent) {
  function renderWrappedComponent(id) {
    return <WrappedComponent id={id} />
  }
  return (
    <MyContext.Consumer>
      {renderWrappedComponent}
    </MyContext.Consumer>
  )
}

当我切换到 React 16.8 时,此代码出现故障。每当调用 onUpdate 时,都会更新提供程序值。但是,消费者永远不会收到更新后的值。

如果我记录时间线,我可以看到调用了react内部的propagateContextChange方法,但之后没有任何反应。

在 16.8 中,您需要像这样通过渲染道具使用上下文的使用者...

<MyContext.Consumer>
  { context => <YourComponent {...context} /> }
</MyContext.Consumer>

这将要求您重构 HOC,因此...

function ConsumerHOC(WrappedComponent) {
  function renderWrappedComponent(id) {
    return (
      <MyContext.Consumer>
        { value => <WrappedComponent id={id} contextValue={value} /> } // if you don't want to pass through all the context's properties, you can chose which props to pass to the wrapped component
      </MyContext.Consumer>
    )
  }
  return renderWrappedComponent
}

我自己回答的!我只升级了 React,忘了也升级 react-dom。新版react依赖新版react-dom,所以升级打断了react context