React 路由器重定向 - 相同或不同历史对象上的 pushState?

React router redirects - pushState on the same or a different history object?

我正在尝试使用 react-router 1.0.2 在 react 组件中执行重定向。

在我的主 app.js 中,我创建了一个哈希历史记录:

import createHashHistory from 'history/lib/createHashHistory';
const history = createHashHistory();
...
ReactDOM.render(
    <RelayRouter history={history} routes={routes} />,
    document.getElementById('root')
);

当我执行数据库插入时,我想重定向到另一个页面。我使用的是在早期版本中工作的这个,但不再工作了:

import createHashHistory from 'history/lib/createHashHistory';
const history = createHashHistory();
...
// inside Component after a successful DB insert
  history.pushState(null, `/#/albums/${newAlbum.id}`, null);

这是另一个组件 (CreateAlbum)。

我是否需要在同一个历史实例上调用 pushState,如果需要,我如何从一个组件中获取它?如果不是,我做错了什么?地址栏确实更新了,但页面保持不变。

最后,我手动为 URL 添加了前缀 /#/。这很草率,只能与哈希历史一起使用。我在 API 中看到有一个 createHref 方法,但它需要一个未解释的路径名。鉴于相关路线定义如下,我如何使用它以正确的形式生成 URL?

<Route
  component={App}
  queries={ViewerQueries}
  path="/">
  <Route
    path="/create" component={CreateAlbum} />
  <Route
    path="/albums/:albumId" component={AlbumDetails}
    queries={ViewerQueries} />
</Route>

您必须在同一个历史实例上调用它。

如果您在 Route 的组件属性中定义的 Route 组件中调用它,例如您的 AppCreateAlbumAlbumDetails历史对象已经可用 this.props.history,您可以 console.log(this.props.history) 检查它!

所以你可以简单地调用:

this.props.history.pushState(null, `/#/albums/${newAlbum.id}`)

改变路线。

但是如果你想在嵌套组件中调用它,你可以...

将历史作为道具一直传递到您的组件:

<NestedComponent history={this.props.history} />

如果您使用 react-router 1.0.2(1.0.3 后弃用),请使用 history mixin

结帐

如果您使用的是 1.0.4

,请使用 router context's push method

如果您的组件不是很深入,将历史作为 prop 传递可能更容易!

为了扩展 Dax 的回答,

Router 会将历史组件作为 prop 向下传递到其节点 - 因此 this.props.history 将在所有 Route 节点上可用。您不需要为每个组件创建一个新的历史记录对象。

如果您创建一个 non-route 组件,您将需要像 Dax 提到的那样将历史传递到该组件中,或者从历史中传递某种相关的 'event' 函数,因为传递整个对象可能不会完全有必要。

如果您已经在 1.0.x - rackt 刚刚发布了 2.0.0 的 rc,这应该是一个相当顺利的升级。您可以查看 upgrade guide here