如何在我自己的高阶组件 (HOC) 中使用 React Router 的 withRouter HOC? [英] How can I use React Router's withRouter HOC inside my own higher order component (HOC)?
问题描述
我有一个高阶组件,它使用 React Router 提供的 location.search
道具来构造一个 queryParams
对象,并将其作为道具传递给其包装的组件.
I have a higher order component which uses the location.search
prop provided by React Router to construct a queryParams
object and pass it as a prop to its wrapped component.
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
包装在一个路由中:
And of course I'd wrap MyComponent
in a route:
<Route path="/mycomponent" component={MyComponent} />
但是回到我的 withQueryParams
HOC,我想确保 props.location
始终可用,这意味着我希望它始终具有来自反应路由器.输入 withRouter
,它本身是 React Router 提供的 HOC,您可以使用它来使这些 props 可用.
But going back to my withQueryParams
HOC, I'd like to ensure that props.location
is always available, meaning I'd like it always to have props from React Router. Enter withRouter
, which is itself a HOC provided by React Router that you can use to make those props available.
在我的 withQueryParams
HOC 中使用 withRouter
以确保 props.location
可用的最佳方法是什么?
What would be the best way to use withRouter
inside my withQueryParams
HOC to ensure that props.location
is available?
谢谢.
推荐答案
function withQueryParams(WrappedComponent) {
return withRouter((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
这篇关于如何在我自己的高阶组件 (HOC) 中使用 React Router 的 withRouter HOC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!