
如何在 reactjs 中使用 axios
介绍
axios 是一个流行的库,用于执行 get、post、put、delete 等 http 请求。 axios 非常适合在 react 应用程序中使用,因为它提供简单的语法并支持 promises。本文将讨论如何在 reactjs 应用程序中使用 axios。
axios 安装
确保你的 react 项目中安装了 axios:
npm install axios
在 react 组件中使用 axios
例如,我们希望使用 get 方法从 api 检索数据并将其显示在 react 组件中。
- 获取请求:
import react, { useeffect, usestate } from 'react';
import axios from 'axios';
const app = () => {
const [data, setdata] = usestate([]);
const [loading, setloading] = usestate(true);
const [error, seterror] = usestate(null);
useeffect(() => {
const fetchdata = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
setdata(response.data);
setloading(false);
} catch (error) {
seterror(error);
setloading(false);
}
};
fetchdata();
}, []);
if (loading) return loading...
;
if (error) return error: {error.message}
;
return (
posts
{data.map((post) => (
- {post.title}
))}
);
};
export default app;
说明:
- 在组件首次加载时使用useeffect调用fetchdata函数。
- axios.get 用于从 api url 检索数据。
- 状态数据、加载和错误用于存储检索到的数据、加载状态和错误。
- post 请求: 要向服务器发送数据,可以使用post方法,如下所示:
import React, { useState } from 'react';
import axios from 'axios';
const App = () => {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title,
body,
});
console.log('Response:', response.data);
alert('Post successfully created!');
} catch (error) {
console.error('Error posting data:', error);
}
};
return (
Create a Post
);
};
export default App;
说明:
- axios.post 方法用于将标题和正文数据发送到 api。
- handlesubmit 函数处理表单提交并将数据发送到服务器。










