老师请问当我的数据是一个数组的之后为什么获取不到user值

来源:5-2 前后端联调1

qq_樱花树下的羁绊_0

2017-11-25

在axios 调用后 console.log 发现数据是存在的,可是在render 中无法获取

http://img.mukewang.com/szimg/5a18fee1000165b616041098.jpg

http://img.mukewang.com/szimg/5a18fd2c0001fbf706470262.jpg

http://img.mukewang.com/szimg/5a18fd4b0001c5b205110307.jpg


写回答

1回答

慕瓜8449030

2017-11-26

hi,你好,因为你的 ajax 没返回的时候,data 是空数组,data[1]是不存在的,所以获取 data[1].user会报错,你可以先对 data 做一个长度判断,比如 render 加一行,

if (!this.state.data.lengh){
    return null
}

1
4
qq_孔洁钰May_03759002
class Auth extends React.Component{ constructor(props){ super(props) this.state = { data: {} } } componentDidMount(){ axios.get('/data') .then(res => { console.log(res) if(res.status==200){ this.setState({data:res.data}) } }) } render(){ if(!this.state.data.length){ return null } return (

我的名字是:{this.state.data[0].name}

{ this.props.isAuth? : null}

你没有权限,需要登陆

) } }
2018-12-21
共4条回复

Redux+React Router+Node.js全栈开发

全网唯一的React 16+Redux+React Router4实战课程,学到手是你的真本领!

1822 学习 · 750 问题

查看课程