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

jbr*_*own 3 javascript react-router

我正在尝试使用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')
);
Run Code Online (Sandbox Code Playgroud)

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

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

这是另一个组件(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>
Run Code Online (Sandbox Code Playgroud)

Dax*_*hen 6

您必须在同一个历史记录实例上调用它.

如果您在Route的组件道具中定义的Route组件中调用它,例如您的App,CreateAlbum或者AlbumDetails,历史对象已经可用this.props.history,您可以console.log(this.props.history)检查它!

所以你可以简单地打电话:

this.props.history.pushState(null, `/#/albums/${newAlbum.id}`)
Run Code Online (Sandbox Code Playgroud)

改变路线.

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

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

<NestedComponent history={this.props.history} />
Run Code Online (Sandbox Code Playgroud)

使用history mixin,如果你使用的反应路由器1.0.2(1.0.3之后已弃用)

结帐该SO用于更详细地

使用router contextpush方法,如果你使用1.0.4


如果您的组件不是非常深入,那么将历史作为道具传递可能会更容易!

  • 警告:[react-router]`props.history`和`context.history`已弃用.请使用`context.router`.http://tiny.cc/router-contextchanges (2认同)