1,使用步骤
使用React Toolkit 创建 counterStore(store目录下) --> 为React注入store(src下面的index) --> React组件使用store中的数据(组件)
2,例如下面有一个简单加减的案例
先来看一下项目目录
counterStore代码:
import { createSlice } from '@reduxjs/toolkit'
const counterStore = createSlice({
// 模块名称独一无二
name: 'counter',
// 初始数据
initialState: {
count: 1
},
// 修改数据的同步方法
reducers: {
increment (state) {
state.count++
},
decrement(state){
state.count--
}
}
})
// 结构出actionCreater
const { increment,decrement } = counter.actions
// 获取reducer函数
const counterReducer = counterStore.reducer
// 导出
export { increment, decrement }
export default counterReducer
store下面 index 的代码:
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './modules/counterStore'
export default configureStore({
reducer: {
// 注册子模块
counter: counterReducer
}
})
src下面index 的代码:
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
// 导入store
import store from './store'
// 导入store提供组件Provider
import { Provider } from 'react-redux'
ReactDOM.createRoot(document.getElementById('root')).render(
// 提供store数据
<Provider store={store}>
<App />
</Provider>
)
App的代码:
import { useSelector, useDispatch } from 'react-redux'
import {decrement,increment} from './store/modules/counterStore'
function App(){
const dispatch = useDispatch()
// 错误使用
// const count = useSelector(state=>state.counter)
// 正确使用
const {count} = useSelector(state=>state.counter)
return (
<div>
<button onClick={()=>dispatch(decrement())}>-</button>
<h1>
{count}
</h1>
<button onClick={()=>dispatch(increment())}>+</button>
</div>
);
}
export default App;
页面是这样的,点击加减数字就会改变了