Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React router redirects-相同或不同历史对象上的pushState?_Javascript_React Router - Fatal编程技术网

Javascript React router redirects-相同或不同历史对象上的pushState?

Javascript React router redirects-相同或不同历史对象上的pushState?,javascript,react-router,Javascript,React Router,我正在尝试使用react router 1.0.2在react组件中执行重定向 在我的mainapp.js中,我创建了一个哈希历史记录: import createHashHistory from 'history/lib/createHashHistory'; const history = createHashHistory(); ... ReactDOM.render( <RelayRouter history={history} routes={routes} />,

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

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

import createHashHistory from 'history/lib/createHashHistory';
const history = createHashHistory();
...
ReactDOM.render(
    <RelayRouter history={history} routes={routes} />,
    document.getElementById('root')
);
这在另一个组件(
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的组件道具中定义的路由组件中调用它,例如您的
应用程序
CreateAlbum
AlbumDetails
历史对象已可用作
this.props.history,您可以
console.log(this.props.history)
来检查它

因此,您可以简单地调用:

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

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

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

如果您使用的是react router 1.0.2(1.0.3之后已弃用),请使用 结帐

如果使用的是1.0.4,请使用

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

要扩展Dax的答案

路由器将历史组件作为道具传递给其节点-因此
this.props.history
将在所有路由节点上可用。您不需要为每个组件创建新的历史对象

如果您创建一个非路由组件,您将需要像Dax提到的那样将历史传递到该组件中,或者从历史传递某种相关的“事件”函数,因为传递整个对象可能不是完全必要的


如果您已经使用了1.0.x,rackt刚刚发布了rc for 2.0.0,这应该是一个相当顺利的升级。您可以查看警告:[react router]
props。历史记录
和上下文。历史记录
不推荐使用。请使用
context.router
this.props.history.pushState(null, `/#/albums/${newAlbum.id}`)
<NestedComponent history={this.props.history} />