发布于 2026-01-06 0 阅读
0

React Redux API 调用示例:构建 CRUD 应用 延伸阅读

React Redux API 调用示例:构建 CRUD 应用

延伸阅读

在本教程中,我将向您展示如何构建一个基于 React Redux 的示例,并通过 API 调用来使用 REST API 进行 CRUD 操作。您还可以使用 Router、Axios 和 Bootstrap 来显示和修改数据。

完整文章:https://bezkoder.com/react-redux-crud-example/

React Redux 示例概述及 API 调用

我们将构建一个包含 API 调用的 React Redux 教程应用程序:

  • 每个教程都有 id、标题、描述、发布状态。
  • 我们可以创建、检索、更新、删除教程。
  • 您可以使用搜索栏按标题查找教程。

以下是我们的 React Redux CRUD 应用程序的屏幕截图。

  • 创建项目:

react-redux-example-api-calls-axios-create-tutorial

  • 检索所有项目:

react-redux-example-api-calls-axios-retrieve-tutorial

  • 点击“编辑”按钮更新项目:

react-redux-example-api-calls-axios-retrieve-one-tutorial

在本页面,您可以:

  • 使用“发布”按钮将状态更改为“已发布”。
  • 使用“删除”按钮删除该项目
  • 使用“更新”按钮更新商品详情

react-redux-example-api-calls-axios-update-tutorial

  • 按标题搜索教程:

react-redux-example-api-calls-axios-search-tutorial

  • Redux Store:

react-redux-example-api-calls-axios-store

此 React 客户端使用以下 Web API:

方法 网址 行动
邮政 /api/tutorials 创建新教程
得到 /api/tutorials 检索所有教程
得到 /api/tutorials/:id 获取教程:id
/api/tutorials/:id 更新教程:id
删除 /api/tutorials/:id 删除教程:id
删除 /api/tutorials 删除所有教程
得到 /api/tutorials?title=[关键词] 查找标题包含以下内容的所有教程keyword

您可以在以下文章中找到搭建类似服务器的详细步骤:

React Redux 应用组件图(含路由和 Axios)

现在来看一下我们将要实现的 React 组件:

react-redux-example-api-calls-axios-components

App组件是一个使用 React 构建的容器Router,它navbar链接到不同的路由路径。

– 三个组件,它们将操作分发给调用REST API 的用户。Redux Thunk MiddlewareTutorialDataService

  • TutorialsList组件获取并显示教程。
  • Tutorial该组件具有用于根据以下内容编辑教程详细信息的表单:id
  • AddTutorial组件包含用于提交新教程的表单。

用于TutorialDataService发出axiosHTTP 请求和接收响应。

React Redux API 调用示例

此图展示了 Redux 元素在我们的 React 应用中的工作原理:

react-redux-example-api-calls-axios-redux-store-architecture

我们将创建 Reduxstore来存储tutorials数据。其他 React 组件将通过分发一个action.

它将reducer采取行动并返回新的state

改用 Redux Toolkit:
Redux-Toolkit 示例

技术

  • React 17/16
  • react-redux 7.2.3
  • redux 4.0.5
  • redux-thunk 2.3.0
  • react-router-dom 5.2.0
  • axios 0.21.1
  • Bootstrap 4

项目结构

react-redux-example-api-calls-axios-project-structure

我简要解释一下。

  • package.json包含主要模块react,,,,,react-router-domreact-reduxreduxredux-thunkaxiosbootstrap
  • AppRouter是带有导航栏的容器。
  • 共有 3 个组成部分TutorialsList,,TutorialAddTutorial
  • http-common.js使用 HTTP 基本 URL 和标头初始化 axios。
  • TutorialDataService具有向 API 发送 HTTP 请求的方法。
  • .env文件配置此 React CRUD 应用的端口。

我们将用到的 Redux 元素:

  • actions文件夹包含操作创建器(tutorials.js用于 CRUD 操作和搜索)。
  • reducers文件夹包含 reducer(tutorials.js),它会更新与分发的操作相对应的应用程序状态。

更多步骤和 GitHub 源代码请访问:
https://bezkoder.com/react-redux-crud-example/

如果您想改用 Redux-Toolkit,请访问:
Redux-Toolkit CRUD 应用示例

或者,您可以添加分页组件:
使用 Material-UI 的 React 分页 API

react-redux-example-api-calls-axios-pagination

延伸阅读

相关文章:

无服务器:

Docker化:

文章来源:https://dev.to/tienbku/react-redux-example-with-api-calls-build-a-crud-app-281b