基于 TypeScript 的 React 应用中使用 Redux 管理 NPM API 数据

介绍如何在使用 Create React App 创建的 TypeScript React 应用中,利用 Redux 管理从 NPM API 获取的数据。

项目初始化

使用 Create React App 创建一个新的 TypeScript React 项目:

npx create-react-app my-app --template typescript

安装依赖

安装 Redux 和相关依赖:

npm install redux react-redux @reduxjs/toolkit axios

创建 Redux Store

创建一个 Redux store 来存储应用状态,包括从 NPM API 获取的数据。

定义 Action

定义从 NPM API 获取数据的 action。

创建 Reducer

创建 reducer 来处理 action 并更新 store 中的数据。

连接 React 组件

使用 useSelectoruseDispatch hooks 将 React 组件连接到 Redux store。

获取数据

在组件加载时,使用 useEffect hook 从 NPM API 获取数据。

展示数据

在 React 组件中展示从 Redux store 获取的数据。

zip
fetch-npm-api-redux-typescript-master.zip 预估大小:24个文件
folder
fetch-npm-api-redux-typescript-master 文件夹
file
.gitignore 310B
file
package.json 1KB
file
package-lock.json 643KB
folder
src 文件夹
folder
components 文件夹
file
RepositoriesList.tsx 865B
file
App.tsx 299B
folder
state 文件夹
file
store.ts 201B
file
index.ts 106B
folder
reducers 文件夹
file
repoReducer.ts 756B
file
index.ts 331B
folder
actions 文件夹
file
index.ts 428B
folder
action-creators 文件夹
file
index.ts 860B
folder
action-types 文件夹
file
index.ts 196B
folder
hooks 文件夹
file
useActions.ts 263B
file
useTypedSelector.ts 189B
file
index.tsx 209B
folder
public 文件夹
file
robots.txt 67B
file
logo192.png 5KB
file
index.html 2KB
file
favicon.ico 4KB
file
manifest.json 492B
file
logo512.png 9KB
file
tsconfig.json 535B
file
README.md 2KB
file
yarn.lock 525KB
zip 文件大小:391.1KB