【问题标题】:After upgrading react 16.2 to 16.8, context consumers receive previous value instead of current将 react 16.2 升级到 16.8 后,上下文消费者会收到以前的值而不是当前值
【发布时间】:2019-05-13 19:44:09
【问题描述】:

我一直在使用 react 16.2,并且 context 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 方法被调用,但之后没有任何反应。

【问题讨论】:

    标签: javascript reactjs react-context


    【解决方案1】:

    我自己回答的!我只升级了 react,忘了升级 react-dom。新版本的 react 依赖于新版本的 react-dom,所以升级破坏了 react 上下文。

    【讨论】:

    • 把对你最有帮助的答案写出来
    【解决方案2】:

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

    【讨论】:

    • 不幸的是,这个重构没有解决我的问题。
    • 你在哪里称呼你的 HOC?
    • 我将 HOC 称为 Provider 的孙子、曾孙等。此设置在 React 16.2 中完美运行。一旦我升级到新的 React 版本,所有消费者都会落后一步更新。但是,消费者都使用正确的初始上下文进行了初始化。
    • 另外,我的上下文值只是一个字符串,而不是一个对象
    • 我刚刚尝试在我的答案中更新 HOC sn-p。您可以再试一次,然后尝试访问 contextValue 作为包装组件中的道具吗?
    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多