如何在React中重定向

时间:2017-10-11 03:30:36

标签: reactjs

我有一个反应应用程序,充当仪表板并显示不同的链接  反应应用程序。用户可以通过单击按钮来选择应用程序 简而言之,我需要根据用户选择重定向到不同的URL。

在下面的示例代码中,尝试使用withRouter重定向到URL。但是它给出了以下错误: TypeError:无法读取未定义

的属性'push'

我正在使用React 15.6.1。

index.js

render(
    <BrowserRouter>
        <Home />
    </BrowserRouter>, document.getElementById('app')
);

home.js

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.loadApp1 = this.loadApp1.bind(this);
    }

    loadApp1() {
        this.props.route.push('/app1');
    }
    render() {
        return (
            <div>
                 <button onClick={this.loadApp1}>App1</button>
            </div>
        );
    }
}

export default withRouter(Home);

2 个答案:

答案 0 :(得分:3)

您可以使用Link执行此操作:

import { Link } from react-router-dom;

然后,

<button><Link to="/app1">App1</Link></button>

将路由到App1路线。

对于外部网站,您可以这样做:

   loadApp1() {
        window.location = "example.com";
    }

答案 1 :(得分:1)

您的loadApp1应该是

 loadApp1() {
    this.props.history.push('/app1');
}