如何将反应上下文 api 与 getDerivedStateFromProps 一起使用?

Ben*_*ung 5 reactjs

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。这很棒!

但我想知道如何将它与 getDerivedFromProps() 一起使用

例如,如果我在应用程序的顶层通过 Context 发送了一个道具,那就说它是window.location.href,并且我需要根据 href 在子组件中采取行动,例如获取数据。

使用 getDerivedStateFromProps(),我必须编写如下内容:

getDerivedStateFromProps(nextProps, state) {

  var stateRev = null
  var pathname = hrefToPath(nextProps.href)
  if (pathname != state.pathname) {
    stateRev = {}
    Object.assign(stateRev, {
      pathname,
      book: source.find()
    })
  }
  return stateRev
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我像上面那样编写代码,则必须通过级别发送 window.location.href。我需要知道的是,如果上下文中的道具发生变化,我需要更新状态。

我认为无法知道上下文中的道具是否发生了变化。关于上下文 api 和 getDerivedStateFromProps 有什么我需要知道的吗?

谢谢你。

Fyo*_*dor 5

如果您想在生命周期方法中使用上下文,您可以使用contextType. 这种方法的问题是它getDerivedStateFromProps是静态的并且无法访问实例变量。

所以我看到的解决方案是将组件包装在高阶组件中,如下所示

const WithContext = (Component) => {
    return (props) => (
        <CustomContext.Consumer>
            {value =>  <Component {...props} value={value} />}
        </CustomContext.Consumer>
    )
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将获得上下文作为 props 的一部分