使用browserHistory的React路由器会在每次更改URL时转到服务器

问题描述 投票:6回答:4

我做的事情如下:

<Router history={browserHistory}>{routes}</Router>

当我在上面的地址栏中的URL更改时,调用将转到服务器,但这不是我想要的,我希望第一次从服务器加载页面,但之后只要路由更改组件只在客户端加载。我在这里错过了什么吗?

在客户端我做的事情如下:

ReactDOM.render(
<Provider store={app.store}>
    <Router history={browserHistory}>{routes}</Router>
</Provider>,
document.getElementById('app'));

我的路线看起来像:

const routes = <Route path="/" component={DJSAppContainer}>
<Route path="page" component={DJSPage}>
<Route path="/page/:pageName" component={PageContainer}/>
</Route>
</Route>;

现在每当我做location.href =“/ page / xyz”时,它都会转到服务器并加载内容。

reactjs react-router jsx
4个回答
6
投票

你不应该直接改变location.href。您应该使用以下命令将新的path发送给React:

ReactRouter.browserHistory.push(newPath);

如果你有锚标签,你应该使用@ ahutch的答案中提到的<Link>组件。


2
投票

React路由器将当前视图中使用的历史记录暴露为道具。查看他们的文档,了解注入here的所有道具。

如果你想从DJSAppContainer或两个孩子中的任何一个重定向DJSPagePageContainer你可以通过访问历史属性来实现:

const {history} = this.props;
history.pushState('/path/to/new/state');

另一方面,如果你做一些花哨的东西,并想从组件外部重定向,试试这个(取自react router docs

// somewhere like a redux/flux action file:
import { browserHistory } from 'react-router'
browserHistory.push('/some/path')

这两种方法假设您尝试基于某些复杂逻辑重定向,而不是单击事件的结果。如果您只想处理点击事件,请尝试使用react-router的<Link/>组件。

似乎历史属性现在已被弃用,并且似乎被implementation of the link component中看到的路由器上下文属性所取代。基本上,如果您真的希望您的代码能够在未来证明,那么您应该要求contextType:

contextTypes: {
     router: object
},

然后从组件的上下文中使用它:

this.context.router.push('/some/path')

1
投票

假设您在后端使用节点,请确保根据react-router docs设置它。

// send all requests to index.html so browserHistory in React Router works
app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'index.html'))
})

此外,当您在组件之间进行链接并且希望确保使用react-router作为路由而不是服务器时,请确保使用Link。希望这能回答你的问题。


0
投票

我遇到了类似的问题,而hashHistory在没有问题的情况下工作,浏览器始终从服务器加载。我通过记住调用preventDefault()来完成工作。这是我的功能:

handleSubmit: function (e) {
    e.preventDefault();
    var username = this.usernameRef.value;
    this.usernameRef.value = '';
    this.context.router.push(`/profile/${username}/`);
}

在onSubmit上的表单上调用handleSubmit。

© www.soinside.com 2019 - 2024. All rights reserved.