需求:页面中没有显示信息时,显示 Loading....,
当获取到 用户信息后,显示 xxx (username) 的邮箱是:xxx( email )
测试接口:http://jsonplaceholder.typicode.com/users
第一步,定义组件并渲染组件标签,
第二步,使用 axious 库 请求数据
注意需要引入 axious 库
效果如下:
页面刚加载时:
渲染请求到的数据时:
完整代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 <script src="../js/react.development.js"></script> 8 <script src="../js/react-dom.development.js"></script> 9 <script src="../js/babel.min.js"></script> 10 <script src="https://cdn.bootcss.com/axios/0.19.2/axios.js"></script> 11 </head> 12 <body> 13 <div id="test"></div> 14 15 <script type="text/babel"> 16 class PersonInfo extends React.Component { 17 state={ 18 usrname:‘‘, 19 email:‘‘ 20 } 21 22 componentDidMount(){ 23 const url="http://jsonplaceholder.typicode.com/users"; 24 axios.get(url) 25 .then(response=>{ 26 console.log(response); 27 const result=response.data[0]; 28 this.setState({ 29 username:result.username, 30 email:result.email 31 }) 32 }) 33 .catch(error=>{ 34 console.log("请求数据失败 "+ error); 35 }) 36 } 37 38 render(){ 39 const {username,email}=this.state; 40 if(username){ 41 return ( <h1>{username}的邮箱是:{email}</h1> ) 42 } 43 else{ 44 return ( <h1>Loading...</h1> ) 45 } 46 } 47 } 48 ReactDOM.render(<PersonInfo/>,document.getElementById("test")); 49 </script> 50 </body> 51 </html>