【问题标题】:TypeError: Cannot read property 'status' of undefined in reactjsTypeError:无法读取 reactjs 中未定义的属性“状态”
【发布时间】:2019-10-08 21:28:40
【问题描述】:

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

 handleSubmit = (e) => {
   e.preventDefault();
   const form = this.props.form;
     const { password, username } = this.state;
   let data = new FormData(); // creates a new FormData object
   data.append('username', form.getFieldValue('username'));
   data.append('password', form.getFieldValue('password'));
   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))

 };

它呈现这个:

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

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

【问题讨论】:

  • 你为什么第二次使用.then? axios.post('127.0.0.1:8000/user/login', data) .then(data => { if(data.status == 200){ history.push('/home');}}) .catch(err=>console.日志(错误))。这应该有效。

标签: reactjs axios push


【解决方案1】:

看不懂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】:

    替换

    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 比较中始终使用等于 (===) 的三元组。

    【讨论】:

      【解决方案3】:

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

      告诉我它是否有效

      【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2019-07-25
      • 2020-06-17
      • 2021-12-06
      • 2022-07-22
      • 2019-05-07
      • 2020-07-30
      相关资源
      最近更新 更多