
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 <p>loading...</p>;
if (error) return <p>error: {error.message}</p>;
return (
<div>
<h1>posts</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default app;
说明:
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 (
<div>
<h1>Create a Post</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
placeholder="Body"
value={body}
onChange={(e) => setBody(e.target.value)}
></textarea>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default App;
说明:
以上就是如何在 ReactJS 中使用 Axios - GET 和 POST 请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号