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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值