首页 > 登录之后react-router的跳转?

登录之后react-router的跳转?

fetch('http://url.com/api/login', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
    hashHistory.push('/home')        //跳转到home
  })    
  .catch(function(error) {
    console.log('request failed', error)
  })

如上代码,登录信息通过API发送出去后,如果成功需要跳转到/home,但这么写似乎不行,因为试了两下,无论成功失败都会跳转。

应该如何写,才能正确判断登录成功与否做不同的动作呢?

如果失败会返回:


401是在then里面。

fetch('http://url.com/api/login', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(function(res) {
    if (res.ok) {
      console.log('request succeeded with JSON response', data)
      hashHistory.push('/home')        //跳转到home
    } else if (res.status == 401) { //处理http状态码
      alert("unauthorized");
    }
  })    
  .catch(function(error) {
    console.log('request failed', error)
  })

@LionKissDeer
紧接着还有个问题,关于消息传递
页面上的header是一个组件,有两个按钮

点击登录,会进入登录页面、填写信息提交、经过上面的ajax请求、返回200,然后需要跳转到/home页面,这时候应该传一个消息到Header组件,让这两个按钮消失并显示已登录的用户名吧?
请问传值的动作在这句代码hashHistory.push('/home')里应该怎么改呢?

最不明白的Header,应该怎样接收Login组件传过来的值,并让两个按钮消失?然后渲染一个新<div>用户名</div>呢?

import React, { Component } from 'react';
import { Link } from 'react-router';

class Header extends Component {
  render() {
    let styles = {
          ....
      }
    }
    return (
      <div style={styles.headerStyle}>
        <Link to="/login" style={styles.linkStyle}>登录</Link>
        <Link to="/signup" style={styles.linkStyle}>注册</Link>
      </div>
    )
  }
}

export default Header;

或者有没有什么案例能参考一下?

【热门文章】
【热门文章】