react-router4.2使用js控制路由跳转的3种方式

1、背景

  • 在不少状况下,咱们须要用js来控制页面的路由切换,而不是经过Link标签这种方式,好比有这样一个场景,用户要登录一个网站才能看到网站里面的内容,登陆接口是一个独立的子页面,登录成功后,才能进入网站浏览相关内容,使用react作SPA时就须要作路由的切换。

2、react-router4.2

  • 在网上随处可见react-router入门使用方式,经过连接绑定组件实现跳转,或者绑定hashHistory后,妄想在子组件中使用this.props.history.push('/某路径')实现路由跳转,诚然,在之前的版本是可行的,听说,反正我没用过。而奇葩的4.2版本并不支持这种方式。我在网上看了许久,试了诸多办法,任然没法经过上述方式实现js控制路由切换,emmm...

3、问题解决办法

使用4.2里面的Redirect标签?组件?,不知道怎么称呼
具体以下:
先定义路由(表):
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom';
 <Router >
      <div style={{height:'100%'}}>
      <Switch>
        <Route exact path="/" component={LoginPage}/>
        <Route path="/chat" component={Chat}/>
        <Route path="/home" component={Home}/>
        <Route path="/login" component={Login}/>
      </Switch>
      </div>
    </Router>)

方法1、在子组件里使用
先要引入Redirectreact

import { Redirect } from 'react-router';

 class Login extends React.Component {
    
    render() {
    const {isRegisterNewUser,loginSuccess}=this.props;
    const { getFieldDecorator} = this.props.form;
    if(loginSuccess){
      *return (<Redirect to="/chat" />);*
    }else{
     return(
     这里放没登录以前的各类form表单
     )
    } 
    
  }
}

方法2、来自下面的大佬:静对94
import PropTypes from 'prop-types';web

static contextTypes = {

    router: PropTypes.object.isRequired,
}

console.log(this.context.router)

例如:redux

class Login extends React.Component {
        static contextTypes = {
            router: PropTypes.object.isRequired,
        }
        render() {
        const {isRegisterNewUser,loginSuccess}=this.props;
        const { getFieldDecorator} = this.props.form;
        if(loginSuccess){//登录状态变为成功
          this.context.router.history.push('/chat)
        }else{
         return(
         这里放没登录以前的各类form表单
         )
        } 
        
      }
    }

方法3、来自Inori_Lover 大佬推荐的官方文档:使用withRouter解决segmentfault

import {withRouter } from 'react-router';
class Login extends React.Component {
            static contextTypes = {
                router: PropTypes.object.isRequired,
            }
            render() {
            const {isRegisterNewUser,loginSuccess,history}=this.props;
            const { getFieldDecorator} = this.props.form;
            if(loginSuccess){//登录状态变为成功
              this.props.history.push('/chat)
            }else{
             return(
             这里放没登录以前的各类form表单
             )
            } 
            
          }
        }
        ...
        
const Login=withRouter(connect(mapStateToProps,mapDispatchToProps)(TLogin))
export default Login;

若是你没有使用redux,那么你使用withRouter的正确姿式应该是api

const Login=withRouter(TLogin)
export default Login;

4、重点就是:

感谢各位大佬的指点,是我太浮躁,没认真阅读文档,之后必定多看。无论什么方式,解决问题才是最重要的。react-router

参考链接:stackoverflowdom

相关文章
相关标签/搜索