简体   繁体   English

在 react.js 中重定向

[英]Redirect in react.js

I am new in react.js.我是 react.js 的新手。 How to do redirect in react.js after login ?登录后如何在 react.js 中重定向? Is it different from Vue.js routing ?它和 Vue.js 路由有什么不同吗? I installed this package.我安装了这个包。 I read this question.我读了这个问题。 I tried in different ways but no one is working.我尝试了不同的方式,但没有人在工作。

Could you please help me with some basic code or any basic tutorial ?你能帮我一些基本的代码或任何基本的教程吗?

Here is my code这是我的代码

import React, { Component } from 'react';
import Auth from '../services/Auth'
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory, Redirect } from 'react-router-dom'

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

        this.handleChange = this.handleChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }
    handleChange (event){
        this.setState({[event.target.name]: event.target.value});
    }
    handleClick(){
        var data = {
            client_id: 2,
            client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f',
            grant_type: 'password',
            username: this.state.email,
            password: this.state.password
        }

        fetch('http://127.0.0.1:8000/oauth/token', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then((response) => response.json())
        .then((responseData) => {

            Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now());

            this.props.history.push("/dashboard");  

        })
    }
}

export default Login;

I am getting error like below我收到如下错误

在此处输入图片说明

There are two way of redirect in React.js. React.js 中有两种重定向方式。

One is using redirect from react-router-dom.一种是使用来自 react-router-dom 的重定向。

And other is using third-party library ie history (this is what you're using) If you're not getting history in your prop then you need to use withRouter.其他正在使用第三方库,即历史记录(这是您正在使用的)如果您没有在道具中获取历史记录,那么您需要使用 withRouter。

example:例子:

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

    class Login extends React.Component {
      handleSubmit = (user) => {
        saveUser(user).then(() =>
          this.props.history.push('/dashboard')
        ))
      }
      render() {
        return (
          <div>
            <h1>Register</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }

    export default withRouter(Login)

For details, refer:详情请参考:

How to redirect in react.js with example 如何使用示例在 react.js 中重定向

Could you please show the errors?你能显示错误吗?

The component seems incomplete to me.该组件对我来说似乎不完整。

If you are using react-router v4, the component should be wrapped with the withRouter .如果您使用的是react-router v4,则组件应该用withRouter包裹。 This passes the history prop to the component.这会将历史道具传递给组件。 Can you please confirm if the history prop is not undefined ?您能否确认history道具是否undefined

Apologies if I misunderstood your question.如果我误解了你的问题,我深表歉意。

First of all, you need to wrap your app ( basically, app ) with BrowserRouter.首先,您需要使用 BrowserRouter 包装您的应用程序(基本上是 app )。 Then you need to define Route for your component.然后你需要为你的组件定义路由。

<Route to='/dashboard' component={dashboard} {...this.props} />

the error you get is because you don't pass the props properly.你得到的错误是因为你没有正确传递道具。

try this:试试这个:

import React, { Component } from 'react';
import Auth from '../services/Auth'
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory, Redirect } from 'react-router-dom'

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

        this.handleChange = this.handleChange.bind(this);
        //this.handleClick = this.handleClick.bind(this);
    }

    handleChange (event) {
        this.setState({[event.target.name]: event.target.value});
    }

    handleClick = (event) => {
        var data = {
            client_id: 2,
            client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f',
            grant_type: 'password',
            username: this.state.email,
            password: this.state.password
        }

        fetch('http://127.0.0.1:8000/oauth/token', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then((response) => response.json())
        .then((responseData) => {

            Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now());

            this.props.history.push("/dashboard");  

        })
    }
}

export default Login;

The difference is an array based function:不同之处在于基于数组的函数:

handleClick = (event) => {}

become:变成:

handleClick (){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM