首页 > 解决方案 > 如何在我自己的高阶组件 (HOC) 中使用 React Router 的 withRouter HOC?

问题描述

我有一个高阶组件,它使用location.searchReact 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} />

但回到我的withQueryParamsHOC,我想确保它props.location始终可用,这意味着我希望它始终拥有来自 React Router 的道具。Enter withRouter,它本身是 React Router 提供的 HOC,您可以使用它来使这些道具可用。

withRouter在我的withQueryParamsHOC 中使用以确保其可用的最佳方式props.location是什么?

谢谢。

标签: javascriptreactjsreact-routerreact-redux

解决方案


您可以使用 HOCwithRouterwithQueryParams. 你可以使用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但它正在接收查询参数,因为我们使用withRouterwithQueryParmsHOC 包装了这个组件。

export const SubComponent = compose(
  withRouter,
  withQueryParams
)(SubComponentView);

现在,如果您SubComponent通过点击 URL https://y493w29lz.codesandbox.io/sub?query=hello来呈现唯一的。它将显示以下输出。

SubComponent
Query Params = {"query":"hello"}

希望这能回答你的问题。:)


推荐阅读