react ts redux 的配置和使用、解决浏览器刷新后数据不存在

安装

npm i @reduxjs/toolkit react-redux

浏览器插件 - Redux DevTools(推荐但不强制使用

src 下创建 store,其中 index.ts/index.js 作为modules中所有store的集合

store/index.ts配置

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({
  reducer: {},
})

// 后续使用useSelector时参数state的类型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

export default store

index.ts或者main.ts中注册store

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
// 添加如下
import store from './store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

现在已经全局注册了redux了

配置

在store/modules中新建counter.ts文件

同步配置

import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0,
}


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

// 这里的actions对应的是上面的reducers function
export const { increment, decrement } = counterSlice.actions

export default counterSlice.reducer

异步

import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}
const initialState: CounterState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  // 同步操作
  reducers: {
   	......
  },
  // 异步操作
  extraReducers(builder){
    // 这里的payload就是incrementAsync的返回值
    builder.addCase(incrementAsync.fulfilled,(state,{payload})=>{
      state.value += payload
    })
  }
})
// 定义异步函数
export const incrementAsync = createAsyncThunk(
  "incrementAsync",
  async(p:number)=>{
  const res = await new Promise<number>(r=>{
    setTimeout(() => {
      r(p)
    }, 1000);
  })
  return res
})

export const { incrementAsync } = counterSlice.actions

export default counterSlice.reducer

在store/index.ts中注册

import { configureStore } from "@reduxjs/toolkit";
// 引入counterSlice.ts
import counterStore  from "./modules/counterSlice";

const store = configureStore({
  reducer:{
  	// 注册,注意名字要与counterSlice.ts中的name一致
    counter:counterStore
  }
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

export default store 

使用

```
// useSelect用于选择操作哪个store

// useDispatch用于生成实例,该实例可以调用reducers的function
import { useSelector, useDispatch } from “react-redux”

// 引入index中的RootState类型 js项目不需要
import { AppDispatch, RootState } from “@/store”

// 引入functions
import { decrement, increment, incrementAsync } from “@/store/modules/counterSlice”

const Demo = () => {
const count = useSelector((state: RootState) => state.counter.value)
const dispatch: AppDispatch = useDispatch() // 异步函数必须加AppDispatch类型,否则报错,同步可以不添加
return (
<>


{count}

<button onClick={() => dispatch(increment())}>+1
<button onClick={() => dispatch(incrementAsync(2))}>+2
<button onClick={() => dispatch(decrement())}>-1
</>
)
}
export default Demo


	
>  原文件地址 https://blog.csdn.net/owo_ovo/article/details/135545732
>	redux中浏览器刷新后数据不存在了,可以存在浏览器缓存中也可以使用插件进行永久花村粗
	react-redux
	#	安装react-redux
npm i redux-persist
# 使用
> src/store/index.js

import { createStore } from ‘redux’
import {persistStore, persistReducer} from ‘redux-persist’
import storage from ‘redux-persist/lib/storage’
//引入汇总之后的reducer
import reducers from ‘./reducers’

import loading from ‘…/redux/reducers/loading’

//在localStorge中生成key为root的值
const persistConfig = {
key: ‘root’,
storage,
blacklist:[‘loading’] //设置某个reducer数据不持久化,
//注意单词的拼写!我就因为写错单词,找了半天,55555~

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 16:56:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 16:56:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 16:56:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 16:56:04       20 阅读

热门阅读

  1. 科目一笔记

    2024-04-21 16:56:04       18 阅读
  2. iOS知识点---Runloop

    2024-04-21 16:56:04       16 阅读
  3. P1990 覆盖墙壁

    2024-04-21 16:56:04       12 阅读
  4. Spring-Aop源码解析(中)

    2024-04-21 16:56:04       16 阅读
  5. ubuntu 22.04 -- cmake安装

    2024-04-21 16:56:04       13 阅读
  6. centos安装服务及设置自启动

    2024-04-21 16:56:04       13 阅读
  7. 产品经理常用工具汇总

    2024-04-21 16:56:04       14 阅读