react.js - react请求到数据后...
本文介绍了react.js - react请求到数据后...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
先上代码:
父组件:
import React,{Component} from 'react'
export default class Father extends Component {
constructor(props){
super(props)
this.state={
role: {}
}
}
componentDidMount() {
fetch("xxxx").then(res=>{
this.setState({
role:res.data.role //获取数据
})
})
}
render(){
return(
<div>
<Child role={this.state.role} /> //将数据传给子组件
</div>
)
}
}
上面是父组件的代码,子组件要通过this.props.role.info.roleName
来获取roleName
显示在页面上。
问题来了:
组件第一次render
的时候,数据还没有请求过来,此时子组件获取的其实是默认的空对象{}
,里面不存在info
,更别说roleName
了,这时就会导致浏览器报错。
这种情况应该如何处理?
解决方案
没有特殊需求的话可以把ajax放到componentWillMount周期。
如果非的是componentDidMount的话,可以给子组件赋值一个defaultProps。
这篇关于react.js - react请求到数据后...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文