一、reduxjs/toolkit
创建store/count.ts
import { createSlice } from "@reduxjs/toolkit";
const counterStore = createSlice({
name: "counter",
initialState: {
count: 0,
},
reducers: {
increment: (state) => {
state.count++;
},
decrement: (state) => {
state.count--;
},
add_num: (state, action) => {
state.count += action.payload;
}
}
});
export const { increment, decrement, add_num } = counterStore.actions;;
export default counterStore.reducer;
export const subAsync = () => {
return async (dispatch: any) => {
setTimeout(() => {
dispatch(decrement());
}, 1000);
}
}
store/index.ts
// 创建store
import { configureStore } from '@reduxjs/toolkit';
import userReducer from './count';
export const store = configureStore({
reducer: {
userReducer,
},
});
main.tsx中全局挂载
import ReactDOM from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import { store } from '@/store/store';
import { Provider } from 'react-redux';
import { Suspense } from 'react';
import AppRoutes from '@/router/router';
import "./index.css";
ReactDOM
.createRoot(document.getElementById('root') as HTMLElement)
.render(
<HashRouter>
<Provider store={store}>
<Suspense fallback={<div>loading</div>}>
<AppRoutes></AppRoutes>
</Suspense>
</Provider>
</HashRouter>
)
在tsx文件中使用
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement,add_num,subAsync } from "./store/count";
const Storage = () => {
const { count } = useSelector(state => state.counter);
const dispatch = useDispatch();
return (<>
<div>{count}</div>
<button onClick={() => dispatch(increment())}>add</button>
<button onClick={() => dispatch(decrement())}>sub</button>
<button onClick={() => dispatch(add_num(6))}>add num</button>
<button onClick={() => dispatch(subAsync(6))}>sub async</button>
</>)
}
export default Storage;
二、zustand
1、store创建好后,可以直接在tsx文件中导入使用
import { create } from 'zustand';
const useStore = create((set) => {
return {
count: 0,
add: () => {
return set(state => ({ count: state.count + 1 }))
},
sub: () => {
return set(state => ({ count: state.count - 1 }))
},
addSync: async () => {
setTimeout(() => {
set((state) => ({ count: state.count + 1 }));
}, 1000);
}
}
})
export default useStore
2、也可以将创建的多个store组合后一起导出
import { create } from 'zustand'
// 创建counter相关切片
const createCounterStore = (set) => {
return {
count: 0,
setCount: () => {
set(state => ({ count: state.count + 1 }))
}
}
}
// 创建channel相关切片
const createChannelStore = (set) => {
return {
channelList: [],
fetchGetList: async () => {
const res = await fetch(URL)
const jsonData = await res.json()
set({ channelList: jsonData.data.channels })
}
}
}
// 组合切片
const useStore = create((...a) => ({
...createCounterStore(...a),
...createChannelStore(...a)
}))
在tsx文件中使用
import useCountStore from '../store/count.js'
import usePersonStore from '../store/person.js'
function App() {
const { count, add, addSync, sub } = useCountStore()
const { person, setName, setAge } = usePersonStore();
return (<>
<div>count:{count}</div>
<button onClick={add}>add</button>
<button onClick={addSync}>addSync</button>
<button onClick={sub}>sub</button>
<div>person:{JSON.stringify(person)}</div>
<button onClick={() => setName('Tom')}>set name</button>
<button onClick={() => setAge(21)}>set name</button>
</>);
}
export default App