react.js - 登录之后react-router的跳转?
本文介绍了react.js - 登录之后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)
})
这篇关于react.js - 登录之后react-router的跳转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文