【问题标题】:Redirect in react.jsreact.js 中的重定向
【发布时间】:2018-10-03 12:06:15
【问题描述】:

我是 react.js 的新手。登录后如何在 react.js 中进行重定向?它与 Vue.js 路由有什么不同?我安装了this 包。我读了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(){
        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;

我收到如下错误

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

React.js 中有两种重定向方式。

一个正在使用来自 react-router-dom 的重定向。

还有其他正在使用第三方库,即历史(这是您正在使用的) 如果您没有在道具中获取历史记录,那么您需要使用 withRouter。

示例:

    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)

详情请参考:

How to redirect in react.js with example

【讨论】:

    【解决方案2】:

    试试这个:

    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;
    

    区别在于基于数组的函数:

    handleClick = (event) => {}
    

    变成:

    handleClick (){}
    

    【讨论】:

      【解决方案3】:

      首先,您需要用 BrowserRouter 包装您的应用程序(基本上是 app )。然后你需要为你的组件定义路由。

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

      你得到的错误是因为你没有正确传递道具。

      【讨论】:

        【解决方案4】:

        能否请您显示错误?

        组件对我来说似乎不完整。

        如果您使用的是react-router v4,则组件应使用withRouter 包装。这会将历史道具传递给组件。请确认history 属性是否不是undefined

        如果我误解了您的问题,我们深表歉意。

        【讨论】:

        • 谢谢@Shishir。我更新了问题。这对你会有帮助。谢谢。
        • 是的。用 withRouter 包裹组件将解决这个问题。如果没有,请告诉我,我会创建一个示例让您了解流程。
        • 谢谢@Shishir。我该怎么做?
        • @abuabu 我创建了一个示例来展示 react-router 的工作原理。 codesandbox.io/s/qlmrxorl66 随意玩弄它。另外,我建议您通过official docs。如果我正确回答了您的问题,请将其标记为答案。 :)
        猜你喜欢
        • 2020-03-13
        • 1970-01-01
        • 2021-05-12
        • 2019-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多