【问题标题】:How to redirect in React如何在 React 中重定向
【发布时间】:2018-03-22 14:28:50
【问题描述】:

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

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

我正在使用 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);

【问题讨论】:

  • 我更新了我的答案。有帮助吗?

标签: reactjs


【解决方案1】:

您可以使用链接来执行此操作:

import { Link } from react-router-dom;

那么,

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

将路由到 App1 路由。

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

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

【讨论】:

  • 我需要路由到这个 react 应用之外的外部应用
  • 我已更新答案以包含外部页面。
  • 感谢@Dream_Cap 很有帮助!
【解决方案2】:

你的loadApp1应该是

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

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2021-03-24
    • 2020-06-22
    • 2020-06-27
    • 2020-11-14
    • 2021-09-13
    • 2017-11-19
    • 2023-01-25
    • 2021-06-13
    相关资源
    最近更新 更多