react 学习之react toolkit状态管理

这只是个简单的例子

首先这是store.ts
import { configureStore } from '@reduxjs/toolkit';
import { counterSlice } from './homeSlice';

// configureStore 创建store
export const store = configureStore({
  reducer: {
    home: counterSlice.reducer
  },
});
counterSlice.ts
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
const initialState = {
  value: 0
}
export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    reset:()=>{
      return { value: 3}
    }
  },
});
//虽然tookit 提供了返回值的处理api但是我还是喜欢在这里处理,个人写法习惯
export const getInfo = createAsyncThunk(
  'counter/getInfo',
  async (_, { dispatch }) => {
    const res = await new Promise(resolve => {
      setTimeout(() => {
        dispatch(counterSlice.actions.reset());
        resolve(2);
      }, 1000);
    });
    return null;
  }
);
// 这是组件的一些调用方法
import { useDispatch, useSelector } from "react-redux";
import { counterSlice } from "../store/homeSlice"
import { useEffect } from "react"
import { getInfo } from "../store/homeSlice";
import { useNavigate } from "react-router-dom";

const Home = () => {
  let valueFromStore = useSelector((state:any) => state.home.value)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  useEffect(() => {
    document.title = valueFromStore.toString();
    // 如果当这个值大于 5 的时候,我们就把这个值重置为 0
    if (valueFromStore > 5 || valueFromStore < 0) {
      dispatch(counterSlice.actions.reset())
    }
  }, [dispatch, valueFromStore]);
  // 调用counterSlice中的getInfo方法
  useEffect(() => {
    dispatch(getInfo() as any);
  }, [dispatch]); 
  const goToAbout = () => {
    navigate('/about');
    // navigate(-1); 返回上一页
  };
  return (
    <>
      <div>
        <button onClick={()=>dispatch(counterSlice.actions.decrement())}>加一</button>
        <button onClick={()=>dispatch(counterSlice.actions.increment())}>减一</button>
        <div>{valueFromStore}</div>
        <button onClick={goToAbout}>去About页面</button>
      </div>
    </>
  )
}
export default Home
// 这是store的挂载部分,入口文件
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import { BrowserRouter } from "react-router-dom";
import { store } from './store/store'

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

  </React.StrictMode>
);

好了,就这么多,每天学习一点点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值