当前位置:   article > 正文

一文搞定react中redux状态管理及使用,redux、reduxjs/toolkit、redux-persist持久化入门_react redux

react redux

本文将从零集中介绍React Redux、Redux Toolkit、redux-persist的使用,全文将以最简单的方式介绍,以便快速上手。

1. 介绍

  • React Redux是React官方提供的Redux绑定库,它提供了一些方便的方法来连接React组件和Redux store。React Redux中文文档
  • Redux Toolkit是一个Redux工具包,它提供了一组方便的方法来简化Redux的开发。Redux Toolkit官方文档
  • redux-persist是一个Redux持久化库,它允许你将Redux store的状态保存到本地存储中,并在需要时将其恢复。redux-persist文档

2. 安装

首先,确保你已经安装了Node.jsnpm或yarn。然后,在项目的根目录下运行以下命令来安装React Redux、Redux Toolkit、redux-persist。

# 如果使用npm
npm install react-redux @reduxjs/toolkit redux-persist

# 如果使用yarn
yarn add react-redux @reduxjs/toolkit redux-persist
  • 1
  • 2
  • 3
  • 4
  • 5

目前这里最新的版本为:

"react-redux": "^9.1.0",
"@reduxjs/toolkit": "^2.2.1",
"redux-persist": "^6.0.0",
  • 1
  • 2
  • 3

3. 配置

3.1 创建store文件夹

目录结构如下:

src
├─ store
 	├─ modules  
		└─ users.js
 	└─ index.js
├─ App.js
└─ index.js
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.2 编写子模块users.js

store/modules/users.js文件中进行
这里会以代码注释的形式进行说明

// 1. 导入Reduxjs Toolkit中的createSlice方法
import { createSlice } from '@reduxjs/toolkit';
// 2. 创建一个名为users的slice
const usersSlice = createSlice({
	 name: 'users',
	 initialState: {
		 list: [],
		 count: 0,
	 },
	 reducers: {
		// 定义一个名为increment的action 因为是同步方法 支持直接修改state
		increment: (state) => {
			// 更新state.count为state.count + 1
			state.count++;
		},
		decrement: (state) => {
			// 更新state.count为state.count - 1
			state.count--;
		},
		// 定义一个名为incrementByAmount的action
		incrementByAmount: (state, action) => {
			// 更新state.count为state.count + action.payload
			state.count += action.payload;
		},
	   // 定义一个名为setUsers的action
	   setUsers: (state, action) => {
	     // 更新state.list为action.payload
	     state.list = action.payload;
	   },
	 },
})
// 3. 解构出来的actionCreater函数
const { increment, decrement, incrementByAmount, setUsers } = usersSlice.actions;

// 模拟异步返回数据
const _callQueryResult = () => {
  const start = new Date().getTime();
  function _generateRandomNumber () {
    return Math.floor(Math.random() * 1000); //生成0到100之间的随机数
  }
  return new Promise(resolve => {
    console.log('%c\n--------响应开始--------', 'color:green;');
    setTimeout(() => {
      const end = new Date().getTime();
      let arr = []
	   // 生成五个随机数
      for (let index = 0; index < 5; index++) {
        arr.push(_generateRandomNumber())
      }
      console.log(`%c--------响应结束--------\n耗时${end - start}ms\n${arr}`, 'color:red;');
      resolve(arr)
    }, 1000)
  })
}
// 异步请求数据
const fetchUsers = () => async (dispatch) => {
	 // 发送异步请求
	 const data = await _callQueryResult();
	 // 派发action,更新state.list
	 dispatch(setUsers(data));
};

// 4. 以按需导出的方式导出actionCreater
export {
	increment,
	decrement,
	incrementByAmount,
	fetchUsers
}
// 5. 以默认导出的方式导出reducer
export default usersSlice.reducer;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71

3.3 统一管理模块index.js

store/index.js文件中进行配置
这里会以代码注释的形式进行说明

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/510740
推荐阅读
相关标签