一、redux
首先安装依赖:
npm install redux react-redux @reduxjs/toolkit
示例代码:
// src/store/index.js
import { configureStore } from '@reduxjs/toolkit'
import couterSlice from './couterSlice'
const store = configureStore({
reducer:{
couterSlice
}
})
export default store
// src/store/couterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const couterSlice = createSlice({
name:'couterSlice',
initialState:{ count: 0 },
reducers:{
increment: (state) => { state.count++ },
decrement: (state) => { state.count++ }
},
extraReducers:(builder) => { }
})
export const { increment,decrement } = couterSlice.actions
export default couterSlice.reducer
// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import { Provider } from 'react-redux'
import store from '@/store'
createRoot(document.getElementById('root')).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
)
具体使用示例:
// src/App.jsx
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { useSelector, useDispatch } from 'react-redux'
import { increment } from '@/store/couterSlice.js'
function App() {
const [count, setCount] = useState(0)
const dispatch = useDispatch()
const counter = useSelector((state) => state.couterSlice)
console.log(counter);
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => dispatch(increment())}>
count is {counter.count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App
持久化存储参考: react-redux 数据持久化-CSDN博客
二、MobX
首先安装依赖:
npm install mobx mobx-react-lite
示例代码:
// src/store/index.js
import React from 'react'
import counter from './counterStore'
class RootStore {
constructor() {
this.counterStore = counter
}
}
const rootStore = new RootStore()
const context = React.createContext(rootStore)
const useStore = () => React.useContext(context)
export { useStore }
// src/store/counterStore.js
import { makeAutoObservable } from 'mobx'
class CounterStore {
count = 0
constructor() {
makeAutoObservable(this)
}
addCount = () => {
this.count++
}
get Count() {
return this.count
}
}
const counter = new CounterStore()
export default counter
// src/App.jsx
import { observer } from 'mobx-react-lite'
import { useStore } from './store'
function App() {
const store = useStore()
return (
<div className="App">
<button onClick={() => store.counterStore.addCount()}>
{store.counterStore.count}
</button>
</div>
)
}
export default observer(App)