安装
npm install react-redux
npm install @reduxjs/toolkit react-redux
import {createSlice} from '@reduxjs/toolkit' //使用 createSlice 创建 Redux "切片" reducer
const counterStore = createSlice({
name:"counter",
// 初始化state
initialState:{
count:0
},
// 修改数据的方法 同步的方法
reducers:{//。通过 createSlice,你可以定义一个状态的初始值(initialState)、一组修改状态的函数(reducers)
increment(state){
state.count++
},
decrement(state){
state.count--
}
}
})
// 解构出actions
const {increment,decrement} = counterStore.actions //虽然 createSlice 主要是用来定义 reducer 的,但是它也负责生成 actions,因此你会在 createSlice 的返回值中看到 actions 属性。
// 获取reducer
const reducer = counterStore.reducer
// 按需导出actionCreater
export {increment,decrement}
// 默认导出reducer
export default reducer //只允许有一个默认导出
import { configureStore } from "@reduxjs/toolkit"; //configureStore 接受一个名为 reducer 的函数作为命名参数;configureStore 会自动使用良好的默认设置来设置 store
import counterReducer from './modules/counterStore'
configureStore({
reducer:{
counter:counterReducer
}
})
export default store
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import {Provider} from 'react-redux'
import store from './store/index.js'
createRoot(document.getElementById('root')).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
)
展示数据
修改数据
import {useDispatch,useSelector } from "react-redux";
import {increment,decrement} from './store/modules/counterStore'
function App() {
const {count} = useSelector(state =>state.counter)
const dispatch = useDispatch()
return (
<>
<button onClick={()=>dispatch(decrement())}>-</button>
{count}
<button onClick={()=>dispatch(increment())}>+</button>
</>
)
}
export default App