gpt4 book ai didi

reactjs - BrowserRouter 与带有 History.push() 的 Router

转载 作者:行者123 更新时间:2023-12-03 13:08:31 30 4
gpt4 key购买 nike

我试图了解 react-router-dom (v5) 包的 BrowserRouterRouter 之间的区别以及它们之间的区别下面是我的例子。

文档说:

BrowserRouter A that uses the HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.

来源:https://reacttraining.com/react-router/web/api/BrowserRouter

Router The common low-level interface for all router components. Typically apps will use one of the high-level routers instead: BrowserRouter, HashRouter, MemoryRouter, NativeRouter, StaticRouter

来源:https://reacttraining.com/react-router/web/api/Router

据我了解,我应该为我的 HTML5 浏览器应用使用 BrowserRouter,而且到目前为止我一直在这样做。

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();

并且历史记录也传递到我的路由器:

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';

最佳答案

BrowserRouter 会忽略历史记录,因为它会自动为您处理历史记录。如果您需要访问 React 组件之外的历史记录,那么使用 Router 应该没问题。

关于reactjs - BrowserRouter 与带有 History.push() 的 Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56707885/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com