【发布时间】:2020-12-16 02:35:03
【问题描述】:
我需要在 React 组件之外重定向用户,这通常使用 history 和 react-router 来完成。
// history.js
const history = createBrowserHistory();
export default history;
// App, setting up router
import { HashRouter as Router } from 'react-router-dom';
import history from './history';
...
<HashRouter history={history}>...</HashRouter> // problem
// Non-component file
import history from './history';
history.push('/target');
由于HashRouter 不采用历史道具,而是在内部处理历史记录,并且开发人员被指示使用withRouter 以将history 暴露给组件,因此如何在外部进行重定向并不明显一个组件。
我正在使用HashRouter 并且我需要在组件外部使用history(这意味着我不能使用withRouter)。
我怎样才能做到这一点?
【问题讨论】:
标签: react-router react-router-dom react-router-v4