Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - BrowserRouter vs Router with history.push()

I am trying to understand the difference between BrowserRouter and Router of the react-router-dom (v5) package and what difference it makes for my example below.

The documentation says:

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

Source: 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

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

From what I understand is that I should be using BrowserRouter for my HTML5 browser apps and I have been doing this so far.

history.push(...) example:

I am trying to perform a history.push('/myNewRoute') within a thunk:

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 is defined as this module:

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

and the history is also passed to my router:

import { BrowserRouter as Router } from 'react-router-dom';
import history as './history';

...

const App = () => (
  <Router history={history}>
     ...
  </Router>
);

Problem: history.push() will update the URL in the browser bar but not render the component behind the route.

If I import Router instead of BrowserRouter, it works:

// Does not work:
import { BrowserRouter as Router } from 'react-router-dom';

// Does work:
import { Router } from 'react-router-dom';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

BrowserRouter ignores the history prop as it handles the history automatically for you. If you need access to the history outside of a react component, then using Router should be fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...