React中的Redux状态管理使用
在React中状态管理常常使用Redux,将两者连接在一起,可以使用react-redux库
简单来说,通过redux将整个状态存储到store中,组件可以派发dispatch行为action给store,其他组件可以通过订阅store中的状态state来更新自身的视图
1.环境创建
在React中使用Redux,官方要求安装两个插件:Redux Toolkt 和react-redux
npm i @redux/toolkit react-redux
关于store的目录结构,可以分为两级,如下:
通常集中状态管理的部分都会单独创建一个'store'目录,而应用通常会有很多个子模块,所以创建一个'modules'目录,在内部编写业务分类的子store,store入口文件index.js的作用是组合modules中所有的子模块,并导出store;
2.React和Redux
在Redux store中,需要配置1.counterStore模块。2.根store并组合counterStore模块
在React组件中需要进行: 1.注入store(react-redux)。2.使用store中的数据。3.修改数据
举个例子,实现一个按下按钮变化数字的功能:
import { createSlice } from '@reduxjs/toolkit'
const counter = createSlice({
name: 'counter',
//初始状态数据
initialState: {
count: 0
},
//修改状态的方法,支持直接修改
reducers: {
inscrement (state) {
state.count++
},
decrement (state) {
state.count--
}
}
})
//解构出来actionCreater函数
const { inscrement, decrement } = counter.actions
//获取reducer
const reducer = counter.reducer
//以按需导出的方式导出actionCreater
export { inscrement, decrement }
//以默认导出的方式导出reducer
export default reducer
这是counter.js的代码,initialState是初始状态的数据,reducer是修改数据的方法,解构是为了生成action对象进而对数据进行修改
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './modules/counter.js'
//创建根store组合子模块
const store = configureStore({
reducer: {
counter: counterReducer
}
})
export default store
这是store中的index.js的代码,将modules中的子模块进行组合并且导出store
下一步是为React注入store
react-redux负责把两者连接起来,内置Provider组件,通过store参数把创建好的store实例注入到应用中
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store/index.js'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
./src/index.js
在React组件中使用store的数据,需要用到一个钩子函数 useSelector,它的作用是把store中的数据映射到组件中,使用样例如下:
import { useSelector,useDispatch } from 'react-redux';
const { count } = useSelector(state => state.counter)
state.counter中的counter来自于组件中的name;接下来即可使用count拿到值。
如果需要修改store中的数据,需要用到另外一个hook函数-useDispatch,它的作用是生存提交action对象的dispatch函数,样例如下:
import { useSelector,useDispatch } from 'react-redux';
import './index.css'
import { inscrement, decrement } from './store/modules/counter.js'
function App() {
const { count } = useSelector(state => state.counter)
const dispatch = useDispatch()
return (
<div className="App">
<button onClick={() => dispatch(decrement())}>-</button>
{count}
<button onClick={() => dispatch(inscrement())}>+</button>
</div>
)
}
export default App;
app.js
如果需要传参,在reducer的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上
代码很简单,就是在reducer中使用第二个参数。
reducers: {
inscrement (state,action) {
state.count+=action.payload
},
decrement (state) {
state.count--
}
}