【问题标题】:Redirect to another page in reactjs not working重定向到reactjs中的另一个页面不起作用
【发布时间】:2018-01-04 11:42:06
【问题描述】:

我正在尝试在我的 reactjs 项目的成功场景中重定向到另一个页面。我已经尝试了以下方法中解释的方法来做到这一点,但没有成功

this.props.router.push('/home');

this.context.router.push('/home');

this.history.pushState(null, 'home');

browserHistory.push('/home');

以及我在 stackoverflow 上找到的许多其他方式。我怎样才能成功地做到这一点。

我的代码

function handleLoginResponse(response){

    switch (response.data.response){

        case "200":
            /**
             * in sccuess senario
             * redirect to the home page
             * set cookies for token and user id create session
             * */

            this.history.pushState(null, 'home');


            break;
        case "201":
            console.log("201");
            break;
        case "202":
            console.log("202");
            break;
        case "203":
            console.log("203");
            break;
        case "204":
            console.log("204");
            break;
        case "205":
            console.log("205");
            break;
        case "206":
            console.log("206");
            break;

    }

}

当我收到“200”的响应时,我想重定向到另一个页面

谢谢。

【问题讨论】:

  • 你的 Rout 组件是什么样的?
  • 你使用的是哪个版本的 react-router?

标签: reactjs redirect react-router


【解决方案1】:

通过简单的方式你可以使用重定向

import { Redirect } from 'react-router'

创建状态,然后将重定向连接到您的状态

例子:

import React, {Component} from 'react'
import { Redirect } from 'react-router'

export default class MyRedirect extends Component{
  constructor(){
    super()
    this.state = {
      redirect : false
    }
  }

  handleLoginResponse(){
    switch(response){
      case '200':
        this.setState({redirect: true})
      break;
    }
  }

  render(){
    return(
      {this.state.redirect && <Redirect to="yourpath" />}
    )
  }
}

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 2020-06-12
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2018-04-29
    • 2013-08-13
    相关资源
    最近更新 更多