React Toolkit使用

史和泰
2023-12-01

React Toolkit

index.ts

import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux'; // 引入react-redux中的自定义组件
import App from './App';
import store from './redux/store'; // 引入公共store

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

// 使用Provider组件包裹App组件
root.render(
    <Provider store={store}> 
      <App />
    </Provider>
);

slice/slice.ts

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

// 异步的任务 要使用特定的createAsyncThunk()包裹
export var loadPic = createAsyncThunk('weather/loadPic', async () => {
    return new Promise((resolve:(str:string)=>void,reject)=>{
        setTimeout(()=>{
            resolve('数据');
        },1000)
    }) // 此处的返回结果会在 .fulfilled中作为payload的值
});

var counterSlice = createSlice({
    name:'counter',
    initialState:{
        value:0 //初始值
    },
    reducers:{ // reducer 方法
        incremented:(state)=>{
            state.value+=1
        },
        decremented:(state)=>{
            state.value-=1
        },
        add:(state,action)=>{
            // action的playload是调用该函数的时候传入的值
            state.value+=action.payload;
        }
    },
    extraReducers:{
        [loadPic.pending.type](state,action:any){
            console.log('pending',state,action);
        },
        [loadPic.fulfilled.type](state,action:any){
            console.log('fulfilled',state,action);
            state.value+=1;
        },
        [loadPic.rejected.type](state,action:any){
            console.log('rejected',state,action);
        },
    }
})
// 暴露方法
export const {incremented,decremented,add} = counterSlice.actions;
export default counterSlice.reducer;

使用:

import React from 'react'
import { useSelector,useDispatch} from 'react-redux' 
import { incremented,decremented,add,loadPic } from '../redux/slices/slices'

const Count = () => {
  const count = useSelector((state:any)=>state.counter.value)
  const  dispatch = useDispatch();
    
    const add=()=>{
      // 加一
      dispatch(incremented())
    }
    const del=()=>{
      // 减一
      dispatch(decremented())
    }
    const asyncAdd=async()=>{
      // 异步加一
      dispatch<any>(loadPic())
    }
  return (
    <div>
      <h2>当前和:{count}</h2>
      <button onClick={add}>加一</button>
      <button onClick={del}>减一</button>
      <button onClick={asyncAdd}>异步</button>
    </div>
  )
}
export default Count
 类似资料: