How to use history

Comprehensive history code examples:

How to use history.index:

865
866
867
868
869
870
871
872
873
874
warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored');
var action = 'PUSH';
var location = createLocation(path, state, createKey(), history.location);
transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
  if (!ok) return;
  var prevIndex = history.index;
  var nextIndex = prevIndex + 1;
  var nextEntries = history.entries.slice(0);

  if (nextEntries.length > nextIndex) {

How to use history.location:

622
623
624
625
626
627
628
629
630
if (path !== encodedPath) {
  // Ensure we always have a properly-encoded hash.
  replaceHashPath(encodedPath);
} else {
  var location = getDOMLocation();
  var prevLocation = history.location;
  if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change.

  if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace.

How to use history.listen:

97
98
99
100
101
102
103
104
105
106
var ref = this.props;
var history = ref.history;
// Do this here so we can setState when a <Redirect> changes the
// location in componentWillMount. This happens e.g. when doing
// server rendering using a <StaticRouter>.
this.unlisten = history.listen(function () {
    this$1.setState({
        match: this$1.computeMatch(history.location.pathname)
    });
});

How to use history.entries:

867
868
869
870
871
872
873
874
875
876
var location = createLocation(path, state, createKey(), history.location);
transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {
  if (!ok) return;
  var prevIndex = history.index;
  var nextIndex = prevIndex + 1;
  var nextEntries = history.entries.slice(0);

  if (nextEntries.length > nextIndex) {
    nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);
  } else {

How to use history.push:

402
403
404
405
406
407
408
409
410
411

- Redirect 路由重定向 是通过 history.replace(props.to) 实现的

- Switch 组件 只会渲染一个Child , 值得注意的是 Redirect 作为Switch 的子Child 当 props.from 与当前location 匹配时 会触发 Redriect 组件的重定向方法

- Link 组件 是基于a标签封装的组件 ,可自定义 onClick 方法,会阻止a标签的默认行为,如果没有自定义 触发navigate 方法 也就是 history.push(props.to)

x. 首先这些api 都是组件 并且都是 extends React.Component ,说白了就是我们平时写的组件,但是是用的es5 的语法所以有点 难懂,当然源码当中,各种封装的方法也是很多,很难阅读

x. 关于 React.createElement 这个api 我介绍下

How to use history.Action:

16
17
18
19
20
21
22
23
24
25
}) {
  if (typeof locationProp === "string") {
    locationProp = history.parsePath(locationProp);
  }

  let action = history.Action.Pop;
  let location = {
    pathname: locationProp.pathname || "/",
    search: locationProp.search || "",
    hash: locationProp.hash || "",

How to use history.createHref:

377
378
379
380
381
382
383
384
385
386
export const Link = React.forwardRef(function(_ref2){
  var _ref2$component = _ref2.component === void 0 ? LinkAnchor : _ref2.component, to = _ref2.to;
  return React.createElement(context.Consumer, null, function (context) {  
    var history = context.history;
    var location = normalizeToLocation(resolveToLocation(to, context.location), context.location);
    var href = location ? history.createHref(location) : "";
    var props = {
      href: href,
      navigate: function navigate() {
        var location = resolveToLocation(to, context.location);

How to use history.parsePath:

140
141
142
143
144
145
146
147
148
149
150
151
function serveIndexWithRouting(req, res, file) {
  const envRequire = isProduction ? require : require('import-fresh')
  const template = envRequire(file)


  const routes = template.routes
  const location = parsePath(req.url)


  return Promise.resolve(routes)
    .then(routes => (routes && routes.match(location, req)) || { status: 200, data: null })
    .then(({ status, headers, data }) =>

How to use history.createPath:

26
27
28
29
30
31
32
33
34
35
  state: locationProp.state || null,
  key: locationProp.key || "default"
};
let staticNavigator = {
  createHref(to) {
    return typeof to === "string" ? to : history.createPath(to);
  },

  push(to) {
    throw new Error(`You cannot use navigator.push() on the server because it is a stateless ` + `environment. This error was probably triggered when you did a ` + `\`navigate(${JSON.stringify(to)})\` somewhere in your app.`);

How to use history.createHashHistory:

0
1
2
3
4
5
/**
 * History
 */

var history = require('history');
module.exports = history.createHashHistory();;

How to use history.replace:

122
123
124
125
126
127
128
129
130
131
editor.script(script);

// Save the script
script.save(function(err) {
  if (err) throw err;
  history.replace(script.url(1, 'edit'));

  // Connect to IO server
  var slug = script.slug(1);
  io.connect(origin + '/' + slug);

How to use history.createLocation:

278
279
280
281
282
283
284
285
286
287
export function Redirect(_ref){ 
  const to = _ref.to

  return React.createElement(context.Consumer, null, function (context) {
    const method = context.history.replace
    const location = history.createLocation(computedMatch ? typeof to === "string" ? generatePath(to, computedMatch.params) : _extends({}, to, {
      pathname: generatePath(to.pathname, computedMatch.params)
    }) : to);  // 路由重定向到to 的地址
    return React.createElement(Lifecycle, {
      onMount: function onMount() {

How to use history.createMemoryHistory:

38
39
40
41
42
43
44
45
46
 *
 * Use MemoryHistory from the 'history' API to store page changes
 * and persist them to the browser, for use in BrowseHistoryComponent
 */

export const MemoryHistory = h.createMemoryHistory({
  initialEntries: recentPages,
  initialIndex: 0,
});

How to use history.createBrowserHistory:

21
22
23
24
25
26
27
28
29
30
        Link = reactRouter.Link;
        Redirect = reactRouter.Redirect;
        useParams = reactRouter.useParams;
        useRouteMatch = reactRouter.useRouteMatch;

        history = createBrowserHistory({ basename: window.basename || '/' });
        // eslint-disable-next-line
        Router = props => <reactRouter.Router {...props} history={history} location={history.location} />;
} catch (e) {
        if (process.env.NODE_ENV !== 'production') {