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 (
    <>
      
{valueFromStore}
) } 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.js,学习,前端)