TypeError:无法读取reactjs中未定义的属性'status'

时间:2019-05-22 11:39:50

标签: reactjs axios push

如果status == 200 ok,我正在尝试推送到/ home,但这给我一个错误。

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}

它呈现以下内容:

master
  

TypeError:无法读取未定义的属性“状态”

3 个答案:

答案 0 :(得分:0)

替换

axios.post('http://127.0.0.1:8000/user/login/', data)
    .then(res=>console.log(res))
    .then(data => { if(data.status == 200){ history.push('/home');}})
    .catch(err=>console.log(err))

axios.post('http://127.0.0.1:8000/user/login/', data)
    .then(res => (res.status === 200) && history.push('/home'));
    .catch(err=>console.log(err))

我建议不要在此处使用data关键字,这会造成歧义,因为您的API结果中包含data关键字。 尝试在js比较中始终使用等于(===)的三倍。

答案 1 :(得分:0)

您无法阅读data.status的原因是data未定义。

要获取数据和状态,您需要返回res,以便在下一个.then中访问

更改此

.then(res=>console.log(res)) // data comes from the return of this function
.then(data => { if(data.status == 200){ history.push('/home');}})

收件人

.then(res => { 
    console.log(res)
    return res // data comes from the return of res
 }) 
.then(data => { if(data.status == 200){ history.push('/home');}})

如果您没有从.then返回任何内容,则下一个.then函数参数将是未定义的。

改写这个answer

  

当您从then()回调返回某些内容时,这有点不可思议。如果返回一个值,则使用该值调用下一个then()。

对于您而言,您将返回console.log(res),但没有status属性

答案 2 :(得分:-1)

替换您的网址: 'http://127.0.0.1:8000/user/login/' 至 'http://127.0.0.1:8000/user/login'

告诉我是否可行

相关问题