Reactjs 如何从数据库中获取数据?
Reactjs 如何从数据库中获取数据?,reactjs,Reactjs,从“React”导入React; 类应用程序扩展了React.Component{ 状态={ 孤岛加载:是的, 用户:[], 错误:null }; fetchUers(){ 取回(“https://randomuser.me/api/") .then((response)=>response.json()) 。然后((数据)=> 这是我的国家({ 用户:数据, 孤岛加载:false }) ) .catch((error)=>this.setState({error,isLoading:false
从“React”导入React;
类应用程序扩展了React.Component{
状态={
孤岛加载:是的,
用户:[],
错误:null
};
fetchUers(){
取回(“https://randomuser.me/api/")
.then((response)=>response.json())
。然后((数据)=>
这是我的国家({
用户:数据,
孤岛加载:false
})
)
.catch((error)=>this.setState({error,isLoading:false}));
}
componentDidMount(){
这是fetchUers();
}
render(){
const{isLoading,users,error}=this.state;
返回(
随机用户
{error?{error.message}:null}
{孤岛加载(
users.map((用户)=>{
const{Image,title,first,last,Gender,address,cell}=用户;
返回(
图像:{Image}
标题:{title}
第一:{first}
最后:{last}
性别:{Gender}
地址:{address}
单元格:{cell}
);
})
) : (
加载。。。。
)}
);
}
}
导出默认应用程序代码>选项1:
fetchUers(){
const self=这个;
取回(“https://randomuser.me/api/")
.then((response)=>response.json())
。然后((数据)=>
自我状态({
用户:数据,
孤岛加载:false
})
)
.catch((error)=>self.setState({error,isload:false}));
}
备选案文2:
fetchUers(){
const handleSuccess=数据=>{
这是我的国家({
用户:数据,
孤岛加载:false
});
}.约束(本);
const handleError=错误=>{
this.setState({error,isLoading:false});
}.约束(本);
取回(“https://randomuser.me/api/")
.then((response)=>response.json())
.然后(handleSuccess)
.接住(把手错误);
}
上下文-“此”在此处不起作用。您必须绑定它,或者在调用方法fetch()之前传递一个引用“this”的变量。谢谢您的回答,如果可能的话,您可以分享它的代码吗?这对我非常有帮助