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)
您必须在同一个历史记录实例上调用它.
如果您在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之后已弃用)router context的push方法,如果你使用1.0.4如果您的组件不是非常深入,那么将历史作为道具传递可能会更容易!
| 归档时间: |
|
| 查看次数: |
10662 次 |
| 最近记录: |