【发布时间】:2019-11-04 13:37:01
【问题描述】:
我试图了解react-router-dom (v5) 包的BrowserRouter 和Router 之间的区别以及它对我下面的示例有何不同。
文档说:
浏览器路由器 使用 HTML5 历史 API(pushState, replaceState 和 popstate 事件)以使您的 UI 与 网址。
来源:https://reacttraining.com/react-router/web/api/BrowserRouter
路由器 所有路由器组件的通用低级接口。通常 应用程序将改为使用高级路由器之一:BrowserRouter、HashRouter、MemoryRouter、NativeRouter、StaticRouter
来源:https://reacttraining.com/react-router/web/api/Router
据我了解,我应该将 BrowserRouter 用于我的 HTML5 浏览器应用程序,到目前为止我一直在这样做。
history.push(...) 示例:
我正在尝试在 thunk 中执行 history.push('/myNewRoute'):
import history as './history';
...
export function someAsyncAction(input) {
return dispatch => {
fetch(`${API_URL}/someUrl`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ input }),
}).then(() => {
history.push('/myNewRoute');
}).catch((err) => {
dispatch(setError(err));
})
};
};
history 被定义为这个模块:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
history 也被传递到我的路由器:
import { BrowserRouter as Router } from 'react-router-dom';
import history as './history';
...
const App = () => (
<Router history={history}>
...
</Router>
);
问题:history.push() 将更新浏览器栏中的 URL,但不会渲染路由后面的组件。
如果我导入 Router 而不是 BrowserRouter,它会起作用:
// Does not work:
import { BrowserRouter as Router } from 'react-router-dom';
// Does work:
import { Router } from 'react-router-dom';
【问题讨论】:
标签: reactjs react-router react-router-dom html5-history