簡體   English   中英

如何在React-Router中使用Javascript重定向頁面?

[英]How to redirect page with Javascript in React-Router?

我在我的應用程序中使用react-router

在我的登錄頁面中,我需要使用ajax身份驗證並在成功時重定向。

有些人喜歡以下代碼:

class PageLogin extends React.Component {
    login() {
        // How to can I redirect to another page if auth success?
    }

    render() {
        return (
            <div className="login-page">
                <form action="">
                    <div className="form-group">
                        <label>Username:</label>
                        <input type="text"/>
                    </div>
                    <div className="form-group">
                        <label>Password:</label>
                        <input type="text"/>
                    </div>
                    <div>
                        <button onClick={this.login}>Login</button>
                    </div>
                </form>
            </div>
        )
    }
}

在我的login功能中,如果驗證成功,如何重定向到另一個頁面?

Context是最好的選擇,但官方文檔告訴您也可以使用withRouterrouter prop添加到您的組件中,以正確執行歷史狀態轉換:

import { withRouter } from 'react-router';

class PageLogin extends React.Component {
    login() {
        this.props.history.push('/some/location'); // for react-router@3 it would be this.props.router.push('/some/location');
    }

    render() {
        return (
            <div className="login-page">
                <form action="">
                    <div className="form-group">
                        <label>Username:</label>
                        <input type="text"/>
                    </div>
                    <div className="form-group">
                        <label>Password:</label>
                        <input type="text"/>
                    </div>
                    <div>
                        <button onClick={this.login}>Login</button>
                    </div>
                </form>
            </div>
        )
    }
}

export default withRouter(PageLogin);

您將在上下文中引用路由器。 您可以使用新的重定向路徑調用router.push

class PageLogin extends React.Component {
  login() {
    this.context.router.push('/newPath');
  }
  ...
 }

PageLogin.contextTypes = {
  router: React.PropTypes.object
}

如果您不想將路線推送到其歷史記錄,而是替換其當前路線,則可以改為調用replace API與push相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM