首页 > 其他分享 >React中store的使用(redux、redux-tookit)及store数据持久化(redux-persist)

React中store的使用(redux、redux-tookit)及store数据持久化(redux-persist)

时间:2023-11-23 10:33:21浏览次数:37  
标签:tookit state persist import redux store const

React中store的使用(redux、redux-tookit)及store数据持久化(redux-persist)

安装

npm insatll react-redux
npm install @reduxjs/toolkit
npm install redux-persist

简单使用store

//counterSlice.js


import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementNum: (state, action) => {
      state.value += action.payload
    }
  }
})

//导出方法
export const { increment, decrement, incrementNum } = counterSlice.actions

//导出reducer
export default counterSlice.reducer
//store.js

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../store/counterSlice'

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
})

export default store
//main.js

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

import { Provider } from 'react-redux'
import { store, persistor } from './app/store.js'
import { PersistGate } from 'redux-persist/integration/react'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <App />
        </PersistGate>
      </Provider>
  </React.StrictMode>
)


使用

//导入
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement, incrementNum } from '../../store/counterSlice'

//在组件中定义
  const dispatch = useDispatch()
  const count = useSelector((state) => state.counter.value)
  
//在页面中使用
  <div className="space-x-2">
      <Button onClick={() => dispatch(decrement())}>减1</Button>
      <span>{count}</span>
      <Button onClick={() => dispatch(increment())}>加1</Button>
      <Button onClick={() => dispatch(incrementNum(5))}>加5</Button>
  </div>

已经可以在react中简单使用仓库了

但是点击刷新时数据会消失,于是需要做数据的持久化

使用中间件redux-persist

只需更改store.js文件,更改后:

import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
// 选择持久化存储引擎,如 localStorage 或 AsyncStorage
import storage from 'redux-persist/lib/storage' // 默认使用localStorage作为存储引擎
import counterReducer from '../store/counterSlice'

const reducer = combineReducers({
  counter: counterReducer
})

// 配置持久化设置
const persistConfig = {
  key: 'root', // 存储的键名
  storage // 持久化存储引擎
  // 可选的配置项,如白名单、黑名单等 选其一就好了
  // blacklist:['test'], // 只有 test 不会被缓存
  // whitelist: ["test"], // 只有 test 会被缓存
}

const persistedReducer = persistReducer(persistConfig, reducer)

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false // 关闭默认的序列化检查//关闭严格模式
    })
})

export const persistor = persistStore(store)

点击刷新数据不会消失了

标签:tookit,state,persist,import,redux,store,const
From: https://www.cnblogs.com/sxliu414/p/17850999.html

相关文章

  • 获取App Store线上应用版本信息
    热烈欢迎,请直接点击!!!进入博主AppStore主页,下载使用各个作品!!!注:博主将坚持每月上线一个新app!!【 注意:中国大陆区用/cn/,如果是其他地区,请把链接改成对应的地区代码。】1、通过AppID:AppStore搜索对应的应用,点击右上角分享按钮,点击拷贝链接,复制到浏览器中,最后的显示的就是十位idh......
  • Pinia对store数据进行的订阅监听
    基本的使用已经记录完毕了,本篇记录Pinia对store数据进行的订阅监听,更直白点说,当store中的state变化到我们想要的那个值时,我们需要去做些什么,那么我们就需要用到$subscribe1.新建vue3项目,安装Pinia,配置Pinia,不再多说了,不会的可以看官网也可以看我前面的几篇记录文章2.app.js--......
  • vuex与redux比较
    相同点state共享数据流程一致:定义全局state,触发,修改state原理相似,通过全局注入store。不同点vuex定义了state、getter、mutation、action四个对象;redux定义了state、reducer、action。vuex触发方式有两种commit同步和dispatch异步;redux同步和异步都使用disp......
  • vue3 使用 store
    在script中使用storehttps://blog.csdn.net/SubStar/article/details/116077737<script>import{getCurrentInstance}from"vue";import{useStore}from"vuex";exportdefault{setup(){//第一种方法:获取路由对象router的方法1constv......
  • OpenWRT/iStoreOS 不重头编译内核安装4G LTE网卡 Quectel EM05-CE记录
    我的机器是x86装了iStoreOS,有4G网卡QuectelEM05https://www.quectel.com/cn/product/lte-em05主要参考资料如下https://www.youtube.com/watch?v=DRddwfZ_TBYhttps://openwrt.org/docs/guide-user/network/wan/wwan/ltedonglehttps://zsien.cn/openwrt-ltedongle/按照视......
  • vuejs3.0 从入门到精通——Pinia——定义Store
    定义Store Store是用defineStore()定义的,它的第一个参数要求是一个独一无二的名字:import{defineStore}from'pinia'//你可以对`defineStore()`的返回值进行任意命名,但最好使用store的名字,同时以`use`开头且以`Store`结尾。(比如`useUserStore`,`useCartStore......
  • vuejs3.0 从入门到精通——Pinia——Store 是什么?
    Pinia——Store是什么?https://pinia.vuejs.org/zh/getting-started.html#what-is-a-store一、Store是什么? Store(如Pinia)是一个保存状态和业务逻辑的实体,它并不与你的组件树绑定。换句话说,它承载着全局状态。它有点像一个永远存在的组件,每个组件都可以读取和写入它。......
  • Angular 应用启用服务器端渲染后 Ngrx store 和 re-hydration 的交互关系
    在Angular启用服务器端渲染(Server-SideRendering,SSR)后,当浏览器端访问这个Angular应用时,会涉及到一系列过程,包括初始化、数据获取、hydration(重新注水)和与NgRxStore之间的交互。下面我将详细介绍这些步骤:初始化应用:用户在浏览器中输入应用的URL。服务器端处理请求,生......
  • 使用ES6生成器(Generators)和redux-saga与使用ES2017的async/await和redux-thunk相比的
    内容来自DOChttps://q.houxu6.top/?s=使用ES6生成器(Generators)和redux-saga与使用ES2017的async/await和redux-thunk相比的优缺点。目前关于redux的最新讨论焦点是redux-saga/redux-saga。它使用生成器函数来监听/分发actions。在我深入研究之前,我想了解使用redux-saga与下......
  • Pset_BuildingStoreyCommon
    Pset_BuildingStoreyCommonBuildingStoreyCommon:IfcBuildingStore所有实例定义的公共属性。请注意,几个建筑属性是在IfcBuildingStorey实例中直接处理的,建筑层数(或短名称)由IfcBuildngStore.name处理,建筑层名称(或长名称)由IFcBuildingStore.LongName处理,描述(或注释)由IccBuildingSt......