0Pricing
React Native Academy · 课时

使用 Axios 发送 POST、PUT 与 DELETE 请求

使用 Axios POST 和 PUT 向 API 发送数据,处理响应以更新本地状态,并实现删除操作,同时从服务器和列表中移除项目。

使用 Axios 发送 POST、PUT 与 DELETE 请求 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

CRUD Operations with Axios

Beyond fetching data, most apps need to create, update, and delete resources on a server. Axios provides axios.post, axios.put, axios.patch, and axios.delete methods that map directly to HTTP verbs. Each method returns a Promise resolving to the server's response.

POST: Creating a New Resource

axios.post(url, data) sends a request body as JSON to create a new resource. The second argument is the request body object — Axios automatically serializes it to JSON and sets the Content-Type: application/json header. The server typically responds with the created resource including its assigned ID.

const createPost = async (title, body) => {
  const response = await axios.post(
    'https://jsonplaceholder.typicode.com/posts',
    { title, body, userId: 1 }
  );
  console.log('Created:', response.data);
  // { id: 101, title: '...', body: '...', userId: 1 }
  return response.data;
};

Adding a New Item to State After POST

After a successful POST, add the returned item to your local state array to reflect the creation without a full re-fetch. Use the functional form of setState to safely merge the new item with the existing array. The server-assigned ID is used as the unique key in subsequent renders.

const handleCreate = async (formData) => {
  try {
    const response = await axios.post('/posts', formData);
    const newPost = response.data;
    setPosts((prev) => [newPost, ...prev]);
  } catch (err) {
    setError('Failed to create post');
  }
};

PUT: Replacing a Full Resource

axios.put(url, data) replaces an entire resource with the provided data. Include the resource's ID in the URL and send all fields in the body. PUT is idempotent — calling it multiple times with the same data produces the same result. Use PUT when you are replacing the complete resource, not just updating a few fields.

const updatePost = async (postId, updatedData) => {
  const response = await axios.put(
    '/posts/' + postId,
    updatedData
  );
  return response.data;
};

PATCH: Partial Update

axios.patch(url, data) sends only the changed fields instead of the entire resource. This is more efficient than PUT when you are updating a single field (like a user's avatar or a post's title). Many REST APIs support both PUT and PATCH — check the API documentation to see which one is expected.

// Only update the title, leave other fields untouched
const patchPostTitle = async (postId, newTitle) => {
  const response = await axios.patch(
    '/posts/' + postId,
    { title: newTitle }
  );
  return response.data;
};

Updating State After PUT/PATCH

After a successful update, replace the old item in the state array with the server's returned version. Use Array.map to iterate over the state and swap the matching item. This keeps the local state in sync with the server without a full re-fetch.

const handleUpdate = async (postId, updatedData) => {
  try {
    const response = await axios.put('/posts/' + postId, updatedData);
    const updatedPost = response.data;
    setPosts((prev) =>
      prev.map((p) => (p.id === postId ? updatedPost : p))
    );
  } catch (err) {
    setError('Failed to update post');
  }
};

DELETE: Removing a Resource

axios.delete(url) removes the resource at the given URL. Most APIs return a 200 or 204 (No Content) response on successful deletion. Unlike POST and PUT, DELETE does not send a request body. The third argument to axios.delete can pass config options like auth headers.

const deletePost = async (postId) => {
  await axios.delete('/posts/' + postId);
  console.log('Post deleted');
};

Removing the Item from State After DELETE

After a successful DELETE, filter the item out of your local state array with Array.filter. The UI updates immediately without a round-trip to re-fetch the full list. If the DELETE fails, the error is caught and the item remains in state — showing the user an error message.

const handleDelete = async (postId) => {
  try {
    await axios.delete('/posts/' + postId);
    setPosts((prev) => prev.filter((p) => p.id !== postId));
  } catch (err) {
    setError('Failed to delete post');
  }
};

Optimistic Updates

Optimistic updates update the local state immediately (before the server confirms) to make the UI feel instant. If the request fails, revert to the original state and show an error. This pattern is used by Twtter's like button and Gmail's delete — the action feels instant even over a slow connection.

const handleDelete = async (postId) => {
  const originalPosts = posts;
  // Update immediately
  setPosts((prev) => prev.filter((p) => p.id !== postId));
  try {
    await axios.delete('/posts/' + postId);
  } catch (err) {
    // Revert on failure
    setPosts(originalPosts);
    setError('Delete failed. Please try again.');
  }
};

Uploading Files with FormData

To upload an image or file via POST, create a FormData object, append the file using the React Native URI format, and pass it to axios.post. Set the Content-Type header to multipart/form-data so the server parses it correctly as a file upload rather than JSON.

const uploadAvatar = async (imageUri) => {
  const formData = new FormData();
  formData.append('avatar', {
    uri: imageUri,
    name: 'avatar.jpg',
    type: 'image/jpeg',
  });

  const response = await axios.post('/user/avatar', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  return response.data.avatarUrl;
};

Chaining Mutations: Create Then Navigate

After a successful POST or PUT, you often want to navigate the user to the newly created resource's detail screen. Chain the navigation call after the state update in the success path of your try/catch. Pass the new resource's ID or the full object as navigation params.

const handleCreatePost = async (formData) => {
  try {
    const response = await axios.post('/posts', formData);
    const newPost = response.data;
    setPosts((prev) => [newPost, ...prev]);
    navigation.navigate('PostDetail', { postId: newPost.id });
  } catch (err) {
    setError('Failed to create post');
  }
};

Quick Check

Test your understanding of POST, PUT, and DELETE requests with Axios from this lesson.

Lesson Recap

In this lesson you learned: axios.post sends a JSON body to create a resource and returns the created item from the server, axios.put/patch replaces or partially updates a resource — update state with Array.map after success, and axios.delete removes a resource — update state with Array.filter and use optimistic updates for a snappy UX. Next up we explore Redux Toolkit for managing complex application state.

常见问题解答

「使用 Axios 发送 POST、PUT 与 DELETE 请求」课时是免费的吗?

是的 — 「使用 Axios 发送 POST、PUT 与 DELETE 请求」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「使用 Axios 发送 POST、PUT 与 DELETE 请求」这节课中我会学到什么?

使用 Axios POST 和 PUT 向 API 发送数据,处理响应以更新本地状态,并实现删除操作,同时从服务器和列表中移除项目。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用 Axios 发送 POST、PUT 与 DELETE 请求」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. useEffect 钩子与依赖数组
  2. 使用 Axios 发起 GET 请求
  3. 处理加载与错误状态
  4. 使用 Axios 发送 POST、PUT 与 DELETE 请求
← 返回 React Native Academy