您可以使用两个 HOC 来包装您的组件,即withRouter
and withQueryParams
。您可以使用重组 https://github.com/acdlite/recompose用这些 HOC 包装您的组件。我为此创建了一个沙箱。https://codesandbox.io/s/y493w29lz https://codesandbox.io/s/y493w29lz
首先,点击https://y493w29lz.codesandbox.io/main https://y493w29lz.codesandbox.io/main。这将在屏幕上显示以下输出。
MainComponent
SubComponent
"No Query Params available"
现在,尝试传递查询参数,例如https://y493w29lz.codesandbox.io/main?query=hello https://y493w29lz.codesandbox.io/main?query=hello。您可以看到查询参数打印在屏幕上。
MainComponent
SubComponent
Query Params = {"query":"hello"}
在这里,组件SubComponent
不是由Route
但它正在接收查询参数,因为我们使用以下方法包装了该组件withRouter
and withQueryParms
HOCs.
export const SubComponent = compose(
withRouter,
withQueryParams
)(SubComponentView);
现在,如果您渲染SubComponent
只需点击 URLhttps://y493w29lz.codesandbox.io/sub?query=hello https://y493w29lz.codesandbox.io/sub?query=hello。它将显示以下输出。
SubComponent
Query Params = {"query":"hello"}
希望这能回答您的问题。 :)