首页 > 解决方案 > 如何将反应上下文 API 与 getDerivedStateFromProps 一起使用?

问题描述

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
}

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

我看不出有什么办法知道上下文中的道具是否改变了。关于上下文 api 和 getDerivedStateFromProps,我有什么需要了解的吗?

谢谢你。

标签: reactjs

解决方案


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

所以我看到的解决方案是将您的组件包装在高阶组件中,就像这样

const WithContext = (Component) => {
    return (props) => (
        <CustomContext.Consumer>
            {value =>  <Component {...props} value={value} />}
        </CustomContext.Consumer>
    )
}

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


推荐阅读