【问题标题】:Redirect doesn't redirect to components重定向不会重定向到组件
【发布时间】:2017-05-26 10:37:05
【问题描述】:

这是我的index.js 页面

import React from 'react';
import ReactDOM from 'react-dom';
import Login from './Login';
import Dashboard from './Dashboard';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import './css/bootstrap.min.css';
import './css/font-awesome.min.css';
import './css/style.css';
import { createHistory, useBasename } from 'history'

const history = useBasename(createHistory)({
    basename: '/'
})   

ReactDOM.render((
  <Router history={history}>
    <div>
       <Route   path="/" component={Login} />
       <Route path="dashboard" component={Dashboard} store={Dashboard} />
       <Route exact path="login" component={Login} store={Login} />
    </div>
  </Router>
),
  document.getElementById('root')
);

这是我的登录页面。但是点击按钮并不会重定向到对应的组件。

import React, { Component } from 'react';
   

export default class Login extends Component {
constructor (props){
        super(props);
        this.state = {
            email : '',
            password : '',
            userId : ''
        };
    }

    login(){
      //this.props.router.push('/dashboard'); // Its was not working
      this.props.history.push('dashboard'); //Its working for me
    }
 render() {
    return (
    <div className="container-fluid">
    <div className="row">
        <div className="col-xl-12">    
            <div className="login-page-block-inner">
                <div className="login-page-block-form">
                        <div className="form-actions">
                            <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                        </div>                       
                </div>
            </div>
        </div>
    </div>
</div>
    );
  }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在您的情况下,this.props.router 将是未定义的。这是我提出的一个粗略的解决方案。阅读代码中的 cmets 会有所帮助。

    import React, { Component } from 'react';
    import { Redirect } from 'react-router-dom'; // add this import 
    
    export default class Login extends Component {
    constructor (props){
            super(props);
            this.state = {
                email : '',
                password : '',
                userId : '',
                redirectToReferrer: true // when you're checking if the user is authenticated you have to keep this false
            };
        }
     //    componentWillReceiveProps(nextProps) {
     //    if ( put your authentication logic here ) {
        //       this.setState({ redirectToReferrer: true });
        //     }
        // }
    
        login(){
          this.props.history.push('/dashboard');
        }
     render() {
        const from = { pathname: '/dashboard' };
        const { redirectToReferrer } = this.state; // redirectToReferrer is true in the initial state
        if (redirectToReferrer) { // if true the user will be redirected to /dashboard
          return <Redirect to={from} />;
        }
        return (
        <div className="container-fluid">
        <div className="row">
            <div className="col-xl-12">    
                <div className="login-page-block-inner">
                    <div className="login-page-block-form">
                            <div className="form-actions">
                                <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                            </div>                       
                    </div>
                </div>
            </div>
        </div>
    </div>
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      在 React 16 及更高版本中,您可以使用 Redirect from 'react-router-dom'

      import  { Redirect } from 'react-router-dom' 
      

      在你的组件中定义状态

      this.state = {
        loginStatus:true
      }
      

      比在你的渲染方法中

      render () {
      if(this.state.loginStatus){
          return <Redirect to='/home'  />
       }
      return(
       <div> Please Login </div>
       )
      }
      

      【讨论】:

        【解决方案3】:

        利用withRouter frun react-router 将路由器作为道具注入您的登录组件

        import React, { Component } from 'react';
        import {withRouter} from 'react-router'
        import $ from 'jquery';
        
        class Login extends Component {
        constructor (props){
                super(props);
                this.state = {
                    email : '',
                    password : '',
                    userId : ''
                };
            }
        
            login(){
              this.props.history.push('/dashboard');
            }
         render() {
            return (
            <div className="container-fluid">
            <div className="row">
                <div className="col-xl-12">    
                    <div className="login-page-block-inner">
                        <div className="login-page-block-form">
                                <div className="form-actions">
                                    <button type="button"  className="btn btn-primary width-150" onClick={(e) => { this.login()} }>Sign In</button>
                                </div>                       
                        </div>
                    </div>
                </div>
            </div>
        </div>
            );
          }
        }
        export default withRouter(Login)
        

        【讨论】:

        • 感谢您宝贵的时间@Shubham。它会抛出类似“Uncaught TypeError: Cannot read property 'push' of undefined”的错误
        • 您是否使用Router 导入并使用它并在创建登录组件之前删除导出默认值
        • 我已经复制并粘贴了您的答案。但它不起作用。
        • 我更新了从 'react-router' 而不是 'react-router-dom' 导入 withRouter 的代码
        • 是的,因为您使用的是自定义历史记录,历史记录是正确的道具
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-21
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多