如何在React中使用Axios





在本文中,您将学习如何在React中使用Axios



让我们使用对服务器的请求示例查看所有内容,在表中显示接收到的数据,通过负载检查组件,以及所有这些都使用React Hooks。



什么是Axios?



Axios是浏览器和基于Promise的node.js最受欢迎的HTTP客户端之一。



Axios支持请求,从服务器接收响应,转换请求并将其自动转换为JSON。



在开始之前,让我们创建一个新的React项目:



npx create-react-app react-axios-table


让我们开始吧:



cd react-axios-table


项目资料



我们将使用对象数组作为项目的数据:



[
	{
		id: 101,
		firstName: 'Sue',
		lastName: 'Corson',
		email: 'DWhalley@in.gov',
		phone: '(612)211-6296',
		address: {
			streetAddress: '9792 Mattis Ct',
			city: 'Waukesha',
			state: 'WI',
			zip: '22178'
		},
		description: 'et lacus magna dolor...',
	}
]


链接到数据



配置组件以与Axios一起使用



加载Axios库:



npm i axios


我们将axios导入到将从中将请求发送到服务器的组件中:



import axios from 'axios'


因为 在项目中,我们使用React Hooks,导入useState和useEffect(在此处阅读更多有关react的钩子的信息):



import React, { useEffect, useState } from 'react';


接下来,将以下代码添加到组件中:



function App() {
  
  const [appState, setAppState] = useState();
  
  useEffect(() => {
    const apiUrl = 'http://www.filltext.com/?rows=32&id={number|1000}&firstName={firstName}&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}';
    axios.get(apiUrl).then((resp) => {
      const allPersons = resp.data;
      setAppState(allPersons);
    });
  }, [setAppState]);

 
  return (
    <div className="app">
    
    </div>
  );
}

export default App;


让我们仔细看一下代码:



const [appState, setAppState] = useState();


负责组件中状态的状态:



 useEffect(() => {}, [setAppState])


useEffect将监视setAppState的更改并在需要时重新呈现



 const apiUrl=''


我们在这里替换我们的链接



axios.get(apiUrl).then((resp) => {
      const allPersons = resp.data;
      setAppState(allPersons);
    });


获取请求发送到服务器,然后接收到的JSON数据保存到状态



下载检查组件



src中创建一个components文件夹在其中,创建UserData.js组件并添加以下代码:

function UserData(props) {

    const { persons } = props

    if (!persons || persons.length === 0) return <p> .</p>

    return (
        <div>
            <table>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>firstName</th>
                        <th>lastName</th>
                        <th>email</th>
                        <th>phone</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        persons.map((person) =>
                            <tr key={person.id}>
                                <td>{person.id}</td>
                                <td>{person.firstName}</td>
                                <td>{person.lastName}</td>
                                <td>{person.email}</td>
                                <td>{person.phone}</td>
                            </tr>
                        )
                    }
                </tbody>
            </table>
      </div>
    )
}

export default UserData


我们将从服务器接收的数据传输到组件的道具。



 if (!persons || persons.length === 0) return <p> .</p>


检查是否有来自服务器的数据



{
                        persons.map((person) =>
                            <tr key={person.id}>
                                <td>{person.id}</td>
                                <td>{person.firstName}</td>
                                <td>{person.lastName}</td>
                                <td>{person.email}</td>
                                <td>{person.phone}</td>
                            </tr>
                        )
                    }


使用map方法,我们与人一起遍历数组,为每个人创建一个字符串。不要忘记钥匙



components文件夹中,创建LoadingPersonsData.js并粘贴以下代码:



function OnLoadingUserData(Component) {
    return function LoadingPersonsData({ isLoading, ...props }) {
        if (!isLoading) return <Component {...props} />

        else return (
            <div>
                <h1>,  !</h1>
            </div>
        )
    }
}

export default LoadingPersonsData


上面的代码是React中的一个高阶组件。它使用另一个组件作为道具,然后返回一些逻辑。在我们的例子中,组件检查isLoading在加载数据时,我们将显示加载消息,当isLoading变为false时,我们将返回包含数据的组件。



让我们对App.js进行更改以能够检查数据加载。



我们将组件导入App.js



import UserData from './components/UserData'
import OnLoadingUserData from './components/OnLoadingUserData'


添加以下代码:



function App() {

  const DataLoading =  LoadingPersonsData(UserData);

  const [appState, setAppState] = useState(
    {
      loading: false,
      persons: null,
    }
  )

 useEffect(() => {
    setAppState({loading: true})
    const apiUrl = 'http://www.filltext.com/?rows=32&id={number|1000}&firstName={firstName}&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}';
    axios.get(apiUrl).then((resp) => {
      const allPersons = resp.data;
      setAppState({
      loading: false,
      persons: allPersons
       });
    });
  }, [setAppState]);


  return (
    <div className="app">
        <DataLoading isLoading={appState.loading} persons={appState.persons} />
    </div>
  );
}

export default App;


 const DataLoading =  LoadingPersonsData(UserData);


我们创建一个新组件,将其等同于我们的高阶组件,并用它包装一个UserData(数据显示组件)。



我们为state添加一个新的属性loading:false,通过它我们将确定服务器中数据的加载。



<DataLoading isLoading={appState.loading} persons={appState.persons} />


渲染组件并将道具传递给我们的高阶组件。



让我们添加一些CSS,在加载数据时,我们将看到以下窗口:



图片



现在,当成功完成对服务器的get请求时,将接收到数据:



图片



现在,我们知道如何将Axios get与REST API结合使用。



如果您有任何问题或建议,请保留在评论中。我很乐意回答。



All Articles