如何在React.js中导航另一个页面以及令牌?

时间:2018-04-08 13:42:08

标签: reactjs

如何导航到另一个页面,其中包含调用“http://localhost:8000/api/polls/1”api的登录用户的详细信息。我如何从这个Login.js导航与“令牌”。我尝试过“navigatetopolls”方法,但它没有用。请帮我解决这个问题

谢谢

import React, { Component } from 'react';
import axios from 'axios';

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

  navigatetopolls(token){
    try {
      const res = fetch('http://localhost:8000/api/polls/1',{
        headers: new Headers({
          'Authorization' : 'Token'+ token

        })
      });
      const polls = res.json();
      console.log(polls)
      this.State= { polls }
    } catch (e) {
      console.log(e);
    }
  }

onChange = (e) => {
    // Because we named the inputs to match their corresponding values in state, it's
    // super easy to update the state
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

onSubmit = (e) => {
    e.preventDefault();
    // get our form data out of state
    const { username, password } = this.state;

    axios.post('http://localhost:8000/api/login/', {
        username: username,
        password: password,
      })
      .then((response) => {
        console.log(response);
        let token =response.data['token'];
        localStorage.setItem("token", token)
        //this.navigatetopolls(token)

      })
      .catch(function (error) {
        console.log(error);
      });
  }

render() {
    const { username, password } = this.state;

    return(
      <form onSubmit={this.onSubmit}>
        <label htmlFor="username">Enter username</label>
        <input name="username" type="text" value={username} onChange={this.onChange}/>

        <label htmlFor="password">Enter your password</label>
        <input name="password" type="password" value={password} onChange={this.onChange}/>

        <button type="submit">Submit!</button>
      </form>
    );
  }
}

export default Login;

0 个答案:

没有答案