【问题标题】:How to redirect page with Javascript in React-Router?如何在 React-Router 中使用 Javascript 重定向页面?
【发布时间】:2017-04-13 13:40:36
【问题描述】:

我在我的应用程序中使用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 函数中,如果身份验证成功,我如何重定向到另一个页面?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您将在上下文中引用路由器。 You can simply call router.push with your new path to redirect.

    class PageLogin extends React.Component {
      login() {
        this.context.router.push('/newPath');
      }
      ...
     }
    
    PageLogin.contextTypes = {
      router: React.PropTypes.object
    }
    

    如果您不想将路由推送到他们的历史记录,而是替换他们当前的路由,您可以call replace instead。 API 与push 相同。

    【讨论】:

    • 这不是 React Router 的当前 API.. 选择的最佳答案是现在的正确用法。
    【解决方案2】:

    上下文是最好的选择,但是官方文档告诉你也可以使用withRouterrouter 属性放到你的组件中,这样可以正确地执行历史状态转换:

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

    【讨论】:

    • 太棒了..!!正是我正在寻找的非常感谢!
    • 链接是404,认为新位置是reacttraining.com/react-router/web/api/Router
    • 对于 v.4.2.0 它是:this.props.history.push('/');
    • 道格和康斯坦丁,谢谢,伙计们!示例中的链接和引用属性现已更新。
    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2017-11-23
    • 2020-07-04
    • 2021-11-12
    • 2022-12-11
    • 2017-05-24
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多