当前位置: 首页 > news >正文

React中Redux的基本用法

Redux是React中使用较多的状态管理库,这篇文章主要介绍了Redux的基本用法,快来看看吧
首先我们需要新建一个React项目,我使用的React+TS,文件结构如下
在这里插入图片描述
Redux的相关使用主要在store文件中

  1. Store:存储整个应用的状态
  2. Action:一个描述发生了什么的JS对象
  3. Reducer:一个纯函数,根据传入的action更新相关的状态
  4. Dispatch:发送action到reducer的方法
  5. Selector:从Store中获取函数的函数

接下来,需要安装相关的包

npm install redux react-redux

之后,我们在相关文件中写相关的规范

  1. types.ts
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
  1. action.ts
import { INCREMENT, DECREMENT } from './types';export const increment = () => ({type: INCREMENT,
});export const decrement = () => ({type: DECREMENT,
});
  1. reducers.ts
import { INCREMENT, DECREMENT } from './types';const initialState = {count: 0,
};const counterReducer = (state = initialState, action) => {switch (action.type) {case INCREMENT:return { ...state, count: state.count + 1 };case DECREMENT:return { ...state, count: state.count - 1 };default:return state;}
};export default counterReducer;
  1. index.js
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import counterReducer from './reducers';const store = createStore(counterReducer, composeWithDevTools());export default store;

之后,我们需要将store提供给React应用来使用,在main.tsx中,进行如下修改

// import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import store from './store/index.ts'
import { Provider } from 'react-redux'createRoot(document.getElementById('root')!).render(// <StrictMode><Provider store={store}><App /></Provider>// </StrictMode>,
)

这样做的目的是,将 Redux Store 注入到整个 React 应用中,这样子组件都可以通过 useSelector 和 useDispatch 访问 Store

接下来,就是在组件中进行使用了,在我们的App.tsx文件中,将相关的方法进行引用

import './App.css'
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './store/action';function App() {// 使用 useSelector 从 Redux Store 获取数据const count = useSelector((state) => state.count);// 使用 useDispatch 发送 actionconst dispatch = useDispatch();return (<><div><h2>Count: {count}</h2><button onClick={() => dispatch(increment())}>Increment</button><button onClick={() => dispatch(decrement())}>Decrement</button></div></>)
}export default App

useSelector() 可以从 Store 中选择数据,然后调用useDispatch() 返回 dispatch 方法,可以触发相关的action,这样就可以成功使用Redux了

但是,在实际开发中,我们大多数情况下都是会处理异步的情况,那么在Redux中如何使用异步呢?由于Redux本身只支持同步数据流,如果处理异步操作,我们需要使用React Thunk中间件
首先需要在store文件夹下边index.ts文件中进行如下修改

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import counterReducer from './reducers';const store = createStore(counterReducer,composeWithDevTools(applyMiddleware(thunk))
);export default store;

接下来就可以在action.ts文件中封装相关的异步操作,案例如下

export const fetchData = () => {return async (dispatch) => {try {const response = await fetch('www.baidu.com');const res = await response.json();dispatch({ type: 'FETCH_SUCCESS', payload: data });} catch (error) {dispatch({ type: 'FETCH_ERROR', payload: error });}};
};

最后在reducers.ts中进行数据返回即可

const initialState = {count: 0,data: null,error: null,
};const counterReducer = (state = initialState, action) => {switch (action.type) {case 'FETCH_SUCCESS':return { ...state, data: action.payload };case 'FETCH_ERROR':return { ...state, error: action.payload };default:return state;}
};export default counterReducer;

以上便是Redux的基本操作,希望可以帮助到你

http://www.lryc.cn/news/488850.html

相关文章:

  • unity3d————基础篇小项目(设置界面)
  • 推荐几个 VSCode 流程图工具
  • 用java和redis实现考试成绩排行榜
  • hhdb数据库介绍(9-24)
  • HDMI数据传输三种使用场景
  • unigui 登陆界面
  • 无人机 PX4飞控 | CUAV 7-Nano 飞行控制器介绍与使用
  • 安装spark
  • 佛山三水戴尔R740服务器黄灯故障处理
  • 大学课程项目中的记忆深刻 Bug —— 一次意外的数组越界
  • html数据类型
  • Kotlin Multiplatform 未来将采用基于 JetBrains Fleet 定制的独立 IDE
  • Redis中常见的数据类型及其应用场景
  • 代理IP在后端开发中的应用与后端工程师的角色
  • 工作流和流程引擎有什么区别?
  • 【SpringBoot】27 拦截器
  • AI对开发者的影响,以及传统软件开发 与 AI参与的软件开发区别
  • HBase Java基础操作
  • 关于一次开源java spring快速开发平台项目RuoYi部署的记录
  • 【AI编程实战】安装Cursor并3分钟实现Chrome插件(保姆级)
  • 【Chatgpt】如何通过分层Prompt生成更加细致的图文内容
  • 中间件--laravel进阶篇
  • 【vue】vue中.sync修饰符如何使用--详细代码对比
  • repmgr安装及常用运维指令
  • RedHat系统配置静态IP
  • nvm和nrm的安装与使用
  • 10大核心应用场景,解锁AI检测系统的智能安全之道
  • 香豆烤馍:传统美食中的烟火记忆
  • 金融量化交易模型的探索与发展
  • 灾难恢复计划 (DRP)