使用React CLI来创建项目,并安装Redux包即可
1、创建React项目:npx create-react-app redux-basic
2、启动项目:yarn start
3、安装Redux包:yarn add redux@3
一、redux核心概念action
1、什么是action
描述要做的事情,项目中的每一个功能都是一个 action
// 计数器案例
{ type: 'increment' } // +1
{ type: 'decrement' } // -1
// 累加10操作
{ type: 'increment', payload: 10 } // +10
{ type: 'decrement', payload: 10 } // -10
2、action creator
使用函数创建 action 对象,简化重复创建action对象。
const increment=(payload)=>{
return {type:'increment',payload}
}
increment(2)
const decrement=(payload)=>{
return {type:'decrement',payload}
}
decrement(2)
二、redux核心概念reducer
1、reducer是函数,用来处理action,是Redux状态更新的地方。
接收上一次的状态和action作为参数,来执行不同操作。函数一定要有返回值。
2、reducer 是一个纯函数
不要使用 Math.random() / new Date() / Date.now() / ajax 请求等不纯的操作
不要让reducer 执行JS副作用
不要直接修改当前状态,而是根据当前状态值创建新的状态值(新替旧)
const reducer = (prevState, action) => {
return newState
}
const increment=(payload)=>{
return {type:'increment',payload}
}
increment(2)
const decrement=(payload)=>{
return {type:'decrement',payload}
}
decrement(2)
const reducer=(state,action)=>{
switch (action.type){
case 'increment': return state+action.payload
case 'decrement': return state-action.payload
default:return state
}
}
console.log(reducer(0,increment(2)));
console.log(reducer(0,decrement(2)));
三、redux核心概念store
1、特点:
(1) 一个应用只有一个store
(2) 维护应用状态,获取状态:store.getState()
(3) 发起状态更新时,需要分发action:store.dispatch(action)
(4) 创建store时接收reducer作为参数:const store=createStore(reducer)
2、其他API
(1) 订阅(监听)状态变化const unSubscribe=store.subcribe(()=>{})
(2) 取消订阅状态变化:unSubscribe()
import { legacy_createStore as createStore } from "redux";
// 第一步:创建store
const store=createStore(reducer)
// 获取store更新状态
console.log(store.getState());
// 第二步:发起更新
store.dispatch(increment(-2))
// 获取store更新状态
console.log(store.getState());
// 随时监听状态变化
const unSubscribe=store.subscribe(()=>{
console.log(store.getState());
})
// 第三步:再次发起更新
store.dispatch(decrement(2))
// 在哪里调用在哪里结束监听
unSubscribe()
react-redux
一、为什么要使用react-redux绑定库
React和Redux是两个独立的库,两者之间职责独立。因此,为了实现在React中使用Redux进行状态管理,就需要一种机制。将这两个独立的库关联起来。这时候就需要React-Redux这个绑定库。
作用:为了React接入Redux,实现在React中使用Redux进行状态管理。
二、react-redux的使用
1、全局配置(只需要配置一次)
2、组件接入(获取状态或者修改状态)
3、步骤
(1)yarn add react-redux
(2)从react-redux中导入Provider组件
(3)导入创建好的redux库
(4)使用Provider包裹整个应用
(5)将导入的store设置为Provider的store属性值
三、react-redux获取状态useSelector
目标:使用useSelector hook获取redux中共享数据状态
内容:useSelector获取redux提供的状态数据
参数:selector函数,用于从Redux状态中筛选出需要的状态数据并返回。返回值是筛选后的数据。
四、react-redux分发动作useDispatch
目标:能够使用useDispatch hook修改redux中共享的状态
内容:useDispatch拿到dispatch函数,分发action,修改redux中的状态数据
五、Redux应用-ActionType的使用
目标:抽离action type
内容:ActionType指的是action对象中的type属性的值