如何获取React组件根组件的实例?

#1

比如一个使用了Redux的React项目,渲染入口像这样:

    const instance = ReactDOM.render((
        <Provider store={store}>
            <Router>
                <Route path="/external/test1" component={Test1} />
                <Route path="/external/test2" component={Test2} />
            </Router>
        </Provider>
    ), node);

    console.log('react instance', instance); // 此时为null

但是当我不使用Redux的时候,比如这样:

    const instance = ReactDOM.render((
            <Router>
                <Route path="/external/test1" component={Test1} />
                <Route path="/external/test2" component={Test2} />
            </Router>
    ), node);

    console.log('react instance', instance); // 此时为Router的实例对象

我应该怎么样去获得带有Redux Provider高阶组件的根组件实例呢?获取到根组件实例之后我可以通过遍历children属性来找到Router实例,从而暴露给外部函数。

我的原始需求是这样的,我需要在React渲染函数外面使用router来做一些事情,比如页面的跳转:

function changeRouter(path) {
    router.history.push(path); // 此处的router为HashRouter或者BrowserRouter的实例
}

在使用HashRouter的时候,我可以不通过这种方法来实现页面跳转,可以直接new一个新的Router实例。而当使用BrowserRouter的时候,如果新new一个的话,实例之间用的不一样的history栈,所以url改变不会引起对应路由组件的渲染。
所以,我需要找到组件中的Router实例,请问有什么方法可以做到这一点吗?

#2
  1. 用 withRouter 可以让任意组件获取到 history
  2. 自己指定history,
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
<Router history={history}>
#3

感谢回复,我试试这种方法。