在react.js中路由问题

时间:2018-04-22 07:10:14

标签: reactjs react-router

我有一个login函数,如下所示。

login(){
    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");
    })
}

我收到以下错误。

enter image description here

更新

我看了this问题并尝试使用 withRouter ,如下所示

import React from "react";
import { withRouter } from "react-router-dom";

class Login extends React.Component {
  ...
  login() {
    this.props.history.push("/dashboard");
  }
  ...
}
export default withRouter(Login);

但我收到了以下错误。

enter image description here

2 个答案:

答案 0 :(得分:1)

请注意,如果您使用的是babel-plugin-transform-decorators,则可以使用以下语法:

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

@withRouter
export default class Test extends React.Component {
    login(){
     this.props.history.push('/Dashboard')
  }
}

或者您只需要查看:withRouter

答案 1 :(得分:0)

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

class ShowTheLocation extends React.Component {

    login(){
     ...
     this.props.history.push('/Dashboard')
    }

    render() {
       return (
         <button onClick={this.login}>Dashboard</button>
       )
    }
  }
}

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

当组件不是路由器的子组件时,它无法访问历史记录。 为了得到历史道具,你必须用 withRouter 包装你的组件 HOC。