反应路由器>重定向不起作用
Posted
技术标签:
【中文标题】反应路由器>重定向不起作用【英文标题】:react-router > redirect does not work 【发布时间】:2016-11-27 05:09:15 【问题描述】:我在互联网上搜索了这个主题,我找到了许多不同的答案,但它们都不起作用。
我想使用 react-router 从代码中真正重定向到“/”路径。 browserHistory.push('/') 代码仅更改 Web 浏览器中的 url,但浏览器不会刷新视图。我需要手动刷新才能查看请求的内容。
'window.location = 'http://web.example.com:8080/myapp/'' 完美运行,但我不想在我的 javascript 代码中硬编码完整的 uri。
能否请您提供一个可行的解决方案?
我使用 react ^15.1.0 和 react-router ^2.4.1。
我的完整示例:
export default class Logout extends React.Component
handleLogoutClick()
console.info('Logging off...');
auth.logout(this.doRedirect());
;
doRedirect()
console.info('redirecting...');
//window.location = 'http://web.example.com:8080/myapp/';
browserHistory.push('/')
render()
return (
<div style=style.text>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick=this.handleLogoutClick.bind(this)>Yes</Button>
</div>
);
【问题讨论】:
【参考方案1】:您可以使用router.push() 而不是使用历史记录。为此,您可以使用上下文或withRouter HoC,这比直接使用上下文更好:
import withRouter from 'react-router';
class Logout extends React.Component
handleLogoutClick()
console.info('Logging off...');
auth.logout(this.doRedirect());
;
doRedirect()
this.props.router.push('/') // use the router's push to redirect
render()
return (
<div style=style.text>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick=this.handleLogoutClick.bind(this)>Yes</Button>
</div>
);
export default withRouter(Logout); // wrap with the withRouter HoC to inject router to the props, instead of using context
【讨论】:
感谢您的回复。它就像一个魅力。我不知道这两种解决方案有什么不同,也许你的工作速度更快。我将使用您的建议。 欢迎。 Router.push 只是路由器使用history.push 的一种方法。没什么花哨的:)【参考方案2】:解决方案:
AppHistory.js
import createHashHistory from 'history';
import useRouterHistory from 'react-router';
const appHistory = useRouterHistory(createHashHistory)(
queryKey: false
);
export default appHistory;
然后,您可以在应用中的任何位置使用 appHistory。
App.js
import appHistory from './AppHistory';
...
ReactDom.render(
<Router history=appHistory onUpdate=() => window.scrollTo(0, 0)>
...
</Router>,
document.getElementById('root')
);
注销.js
import React from 'react';
import appHistory from '../../AppHistory';
import auth from '../auth/Auth';
import Button from "react-bootstrap/lib/Button";
export default class Logout extends React.Component
handleLogoutClick()
auth.logout(this.doRedirect());
doRedirect()
appHistory.push('/');
render()
return (
<div style=style.text>
<h3>Are you sure that you want to log off?</h3>
<Button bsStyle="primary" onClick=this.handleLogoutClick.bind(this)>Yes</Button>
</div>
);
这个话题对我帮助很大: Programmatically navigate using react router
【讨论】:
以上是关于反应路由器>重定向不起作用的主要内容,如果未能解决你的问题,请参考以下文章