react-router>重定向不起作用

时间:2016-07-23 10:57:55

标签: redirect reactjs react-router

我在互联网上搜索了这个主题,我找到了许多不同的答案,但它们只是不起作用。

我想使用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>
        );
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:1)

解决方案:

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')
);

Logout.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