这是我参与「第四届青训营 」笔记创作活动的的第4天
集中式状态管理
运用场景
- 多级路由嵌套,且多个组件公用统一的数据(共享)。
- 组件间需要自由改变数据且每个组件都能看到改变数据(通信)。
- 能不用就不用
原理图
具体实现
1.store.js
用来架起 react和redux的桥梁
import {createStore} from redux
import countReducer from './count_reducer'
export default createStore(countReducer)
2.count_reducers.js
真正来修改redux数据的地方
import {INCREMENT,DECREMENT} from './constant'
const initState = 0
export default function countReducer(preState=initState,action){
const {type,data} = action
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
3.count_action.js
只是用来创建action对象的文件
import {INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})
4.getState
import store from "./store"
store.getState()获得redux里面的值
5.dispatch
store.dispatch({type:'xx',data:xx})通知redux调type函数并传参
6.subscribe
store.subscribe(()=>{this.setState({})})更新视图(store.subscribe会在redux的数据变化时调用)。
或者在index.js里面直接将App重新渲染(推荐)
store.subscribe(createdom(xxx).render(<App/>))
7.redux的异步版本
-
明确:延迟的动作不想交给组件自身,想交给action
-
何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回。
-
具体编码:
1. yarn add redux-thunk,并配置在store中 import {createStore,applyMiddleware} from 'redux' import countReducer from './count_reducer' import thunk from 'redux-thunk' export default createStore(countReducer,applyMiddleware(thunk)) 2.创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。 3.异步任务有结果后,分发一个同步的action去真正操作数据。 -
备注:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action。 变化的是count_action.js文件
export const createIncrementAsyncAction = (data,time) => {
return (dispatch)=>{
setTimeout(()=>{
dispatch(createIncrementAction(data))
},time)
}
}