javascript - 如何在我自己的高阶组件 (HOC) 中使用 React Router 的 withRouter HOC?
问题描述
我有一个高阶组件,它使用location.search
React Router 提供的 prop 来构造一个queryParams
对象并将其作为 prop 传递给它的包装组件。
function withQueryParams(WrappedComponent) {
return (props) => {
const queryParams = myUtils.parseParams(props.location.search); // props.location provided by React Router
const newProps = {
...props,
queryParams: queryParams
}
return <WrappedComponent {...newProps} />
}
}
export default withQueryParams
我会这样使用它:
class MyComponent extends React.Component { ... }
export default withQueryParams(MyComponent)
当然,我会包装MyComponent
一条路线:
<Route path="/mycomponent" component={MyComponent} />
但回到我的withQueryParams
HOC,我想确保它props.location
始终可用,这意味着我希望它始终拥有来自 React Router 的道具。Enter withRouter
,它本身是 React Router 提供的 HOC,您可以使用它来使这些道具可用。
withRouter
在我的withQueryParams
HOC 中使用以确保其可用的最佳方式props.location
是什么?
谢谢。
解决方案
您可以使用 HOCwithRouter
和withQueryParams
. 你可以使用recompose来用这些 HOC 包装你的组件。我为此创建了一个沙箱。https://codesandbox.io/s/y493w29lz
首先,点击https://y493w29lz.codesandbox.io/main。这将在屏幕上显示以下输出。
MainComponent
SubComponent
"No Query Params available"
现在,尝试传递一个查询参数,例如https://y493w29lz.codesandbox.io/main?query=hello。可以看到查询参数打印在屏幕上。
MainComponent
SubComponent
Query Params = {"query":"hello"}
在这里,组件SubComponent
不是由 the 渲染的,Route
但它正在接收查询参数,因为我们使用withRouter
和withQueryParms
HOC 包装了这个组件。
export const SubComponent = compose(
withRouter,
withQueryParams
)(SubComponentView);
现在,如果您SubComponent
通过点击 URL https://y493w29lz.codesandbox.io/sub?query=hello来呈现唯一的。它将显示以下输出。
SubComponent
Query Params = {"query":"hello"}
希望这能回答你的问题。:)
推荐阅读
- c - 我试图用 C 编写一个 Discomfort Index 程序,但我卡住了
- tensorflow - rtx 3090 上的 Tensorflow 1.14 性能问题
- flutter - Auto_route 无法使用生成的文件:没有名为“reportsRouteUpdateToEngine”的名称参数
- apache-spark - 在 EMR 集群上配置 Livy log4j 属性
- python - 使用 docplex CP Optimizer 的 ILP 问题(没有从本地求解器进程中读取)
- c++ - 如何在 C++ COM STA 中的 WebView2 接口上等待对 ExecuteScript 的调用完成
- google-apps-script - 将一系列单元格从一行移动到另一个谷歌工作表并将其删除
- python - Pandas 时间戳在强制转换为唯一列表时转换为整数 - 可能的错误?
- loops - 使用循环时播放回顾不显示所有失败
- performance - 向 Azure 事件中心发送事件时的高延迟