Redux与计数器
- 配套工具
- 使用React Toolkit 创建 counterStore
- 为React注入store
- React组件使用store中的数据
- React组件修改store中的数据
- 绑定用户交互
- 效果展示
- action传参
- Redux异步状态管理
- React中的Redux就像Vue中的Vuex和Pinia一样,都是状态管理工具,通过这种方式可以很方便的实现各个组件中的通信。
- 下面的代码是通过Redux实现一个计数器
配套工具
- 在React中使用Redux,官方要求安装两个插件:
Redux Toolkit
和react-redux
使用React Toolkit 创建 counterStore
import { createSlice } from "@reduxjs/toolkit";const counterStore = createSlice({name:'counter',initialState:{count:0},reducers:{increment(state){state.count++},decrement(state){state.count--}}
})
const {increment,decrement} = counterStore.actions
const reducer = counterStore.reducer
export {increment,decrement}
export default reducer
为React注入store
- react-redux负责把Redux和React连接起来,内置
Provider
组件通过store参数把创建好的store实例注入到应用中
,连接正式建立
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<React.StrictMode><Provider store={store}><App /></Provider></React.StrictMode>
);
React组件使用store中的数据
- 在React组件中使用store中的数据,需要用到一个钩子函数—useSelector,它的作用是把store中的数据映射到组件中
const {count} = useSelector(state=>state.counter)
React组件修改store中的数据
- React组件中修改store中的数据需要借助另外一个hook函数 - useDispatch,它的作用是生成提交action对象的dispatch函数
action传参 - 在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上
Redux异步状态管理 - 步骤:
- 创建store的写法保持不变,配置好同步修改状态的方法
- 单独封装一个函数,在函数内部return一个新函数,在新函数中:
- 封装异步请求获取数据
- 调用同步actionCreater传入异步数据生成一个action对象,并使用dispatch提交
- 组件中dispatch的写法保持不变
绑定用户交互
- 获取状态:通过
useSelector
,组件从Redux store中获取count状态。这里的state.counter假设是store中的一个对象,其中包含count属性。 - 获取
dispatch
函数:通过useDispatch
,组件获取到dispatch函数,这个函数用于将action发送到Redux store。 - 渲染UI:组件渲染两个按钮和当前的count值。点击按钮时,会触发相应的action(increment或decrement),通过
dispatch
函数发送到Redux store,从而更新状态。
import { useSelector,useDispatch } from "react-redux";
import { increment,decrement,addToNum } from "./store/modules/counterStore";
const App = () => {const {count} = useSelector(state=>state.counter)const dispatch = useDispatch()return (<div><button onClick={()=>dispatch(decrement())}>-</button>{count}<button onClick={()=>dispatch(increment())}>+</button></div> );
};export default App;
效果展示

action传参
- 在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上
Redux异步状态管理
- 步骤:
- 创建store的写法保持不变,配置好同步修改状态的方法
- 单独封装一个函数,在函数内部return一个新函数,在新函数中:
- 封装异步请求获取数据
- 调用同步actionCreater传入异步数据生成一个action对象,并使用dispatch提交
- 组件中dispatch的写法保持不变