Redux Toolkit(ts)的基本使用

npm下载

npm install @reduxjs/toolkit react-redux

在src文件夹下创建store文件夹再创建index.js,创建redux

import { configureStore } from '@reduxjs/toolkit'

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

//导出定义的类型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

在index.tsx中通过Provider组件将App组件包裹

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
//引入store和Provider
import {store} from './store/index'
import { Provider } from 'react-redux';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
//将App包裹
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

在store文件夹下创建slice文件夹,再创建counter.ts

import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";

// 定义state中数据的类型
export interface CounterState{
  value:number
}

// 初始化state
const initialState:CounterState={
  value:0
}

export const counterSlice=createSlice({
  name:'counter',
  initialState,
  // 在reducers对state中的数据进行处理
  reducers:{ 
    // 增加
    increment:(state)=>{
      state.value+=1
    },
    // 减少
    decrement:(state)=>{
      state.value-=1
    },
    // 按数量进行增加
    incrementByAmount:(state,action:PayloadAction<number>)=>{
      state.value+=action.payload
    }
  }
})

// 将reducers中的每个写入
export const{increment,decrement,incrementByAmount}=counterSlice.actions

export default counterSlice.reducer

counterSlice导入reducer函数并将其添加到我们的store中。通过在reducer参数,我们告诉store使用这个slicereducer函数来处理该状态的所有更新。

import { configureStore } from '@reduxjs/toolkit'
//添加了这个
import counterReducer from './slice/counter'

// 定义类型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

export const store = configureStore({
  reducer: {
//添加了这个
    couter:counterReducer
  },
})

在src文件夹下创建couter文件夹,创建counter.tsx文件,创建hooks组件

import React,{useState} from 'react'
import { RootState } from '../store'
import {useSelector,useDispatch} from 'react-redux'
import { increment,decrement,incrementByAmount } from '../store/slice/counter'

export default function Counter() {
  // 查询state中的数据
  const count=useSelector((state:RootState)=>state.couter.value)
  // 派发更新reducer中的方法
  const dispatch=useDispatch()
  const [incrementAmount,setIncrementAmount]=useState('2')

  return (
    <div>
      <div>
      {/* aria-label是一个用于为元素提供描述的属性。这个描述旨在帮助屏幕阅读器用户理解该元素的目的或功能。 */}
      
        <button aria-label="增加值" onClick={()=>dispatch(increment())}>+1</button>
        <button aria-label="减少值" onClick={()=>dispatch(decrement())}>-1</button>
        <div>
          {/* 设置增加的大小 */}
          <input value={incrementAmount} onChange={e=>setIncrementAmount(e.target.value)} />
          <button onClick={()=>dispatch(incrementByAmount(Number(incrementAmount)|0))}>增加{incrementAmount}</button>
        </div>
        <hr />
        <div>{count}</div>
      </div>
    </div>
  )
}

异步情况如下

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

// 定义state中数据的类型
export interface CounterState{
  value:number
}

// 初始化state
const initialState:CounterState={
  value:0
}

// 异步增加
export const addAmountAsync=createAsyncThunk(
  'incrementAsync',
  async () => {
    // 返回一个Promise对象,Promise对象的结果类型为number
    const res=await new Promise<number>((resolve)=>{
      setTimeout(()=>{
        resolve(3)
      },3000)
    })
    return res
  }
)

export const counterSlice=createSlice({
  name:'counter',
  initialState,
  // 在reducers对state中的数据进行处理
  reducers:{ 
    // 增加
    increment:(state)=>{
      state.value+=1
    },
    // 减少
    decrement:(state)=>{
      state.value-=1
    },
    // 按数量进行增加
    incrementByAmount:(state,action:PayloadAction<number>)=>{
      state.value+=action.payload
    }
  },
  extraReducers:(builder)=>{
    builder.addCase(addAmountAsync.fulfilled,(state,{payload})=>{
      state.value+=payload
    })
  }
})

// 将reducers中的每个写入
export const{increment,decrement,incrementByAmount,}=counterSlice.actions

export default counterSlice.reducer

import React,{useState} from 'react'
import { RootState,AppDispatch } from '../store'
import {useSelector,useDispatch} from 'react-redux'
import { increment,decrement,incrementByAmount,addAmountAsync } from '../store/slice/counter'

export default function Counter() {
  // 查询state中的数据
  const count=useSelector((state:RootState)=>state.couter.value)
  // 派发更新reducer中的方法
  const dispatch:AppDispatch=useDispatch()
  const [incrementAmount,setIncrementAmount]=useState('2')

  return (
    <div>
      <div>
      {/* aria-label是一个用于为元素提供描述的属性。这个描述旨在帮助屏幕阅读器用户理解该元素的目的或功能。 */}
      
        <button aria-label="增加值" onClick={()=>dispatch(increment())}>+1</button>
        <button aria-label="减少值" onClick={()=>dispatch(decrement())}>-1</button>
        <div>
          {/* 设置增加的大小 */}
          <input value={incrementAmount} onChange={e=>setIncrementAmount(e.target.value)} />
          <button onClick={()=>dispatch(incrementByAmount(Number(incrementAmount)|0))}>增加{incrementAmount}</button>
        </div>
        <div>
          <button onClick={()=>dispatch(addAmountAsync())}>异步增加等3s</button>
        </div>
        <hr />
        <div>{count}</div>
      </div>
    </div>
  )
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值