因为react的render中的return里面只能写表达式,所以在js语法中的for循环和if语句等等,在react中都不能使用
关于for语句,如果需要循环遍历数据,我们可以使用map方法,需要用{}包裹起来
例:
这里的users是多条数据,使用map方法可以遍历这个users
map方法需要设置返回值,返回的就是需要渲染出来的结构,
注意:使用了循环遍历需要设置key值(唯一的id),设置给节点的最外层结构
export default class List extends Component {
render() {
const {users,isFirst,isLoading,err}=this.props
return (
<div className="row">
{
isFirst?<h2>欢迎使用,输入关键字,随后点击搜索</h2>:
isLoading?<h2>isLoading......</h2>:
err?<h2 style={{color:'red'}}>{err}</h2>:
users.map((userObj)=>{
return(
<div className="card" key={userObj.id}>
<a rel='noreferrer' href={userObj.html_url} target="_blank">
<img alt='head_ picture' src={userObj.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}
关于if语句,在react中我们可以使用三目表达式代替if语句,例如上述代码中的实例