reactjs - 如何将反应上下文 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,我有什么需要了解的吗?
谢谢你。
解决方案
如果你想在生命周期方法中使用上下文,你可以使用contextType
. 这种方法的问题是它getDerivedStateFromProps
是静态的,不能访问实例变量。
所以我看到的解决方案是将您的组件包装在高阶组件中,就像这样
const WithContext = (Component) => {
return (props) => (
<CustomContext.Consumer>
{value => <Component {...props} value={value} />}
</CustomContext.Consumer>
)
}
在这种情况下,您将获得上下文作为道具的一部分
推荐阅读
- c++ - 使用 OnComponentHit UE4 C++ 进行碰撞检测
- python - numpy.AxisError:轴 1 超出维度 1 数组的范围
- c++ - 将单例模板应用于具有参数化构造函数的类
- vb.net - 如何在 RichTextBox 中使用 UTF-8?
- spotfire - spotfire 使用 over 函数计算列
- python - 无法在 Windows 机器上启动 Python
- apache - 无法访问此站点 - XAMPP 忽略自定义域虚拟主机
- javascript - 将函数返回保存在 const 中是未定义的
- python - pyqtgraph 中的图像由于缩放而被隐藏
- c - 如何使用指针将输入函数中的 2 个 int,1 个浮点变量输入传递给主函数?