什么是Redux
把所有的state集中到组件顶部,能够灵活的将所有state各取所需的分发给所有的组件
store
- Redux会将整个应用状态(其实也就是数据)存储到到一个地方,称为store
- (单一数据源)整个应用的 state 都被储存在一棵树中,并且这棵状态树只存在于唯一一个 store 中。
- 组件改变state的唯一方法是通过调用store的dispatch方法,触发一个action,这个action被对应的reducer处理,于是state完成更新
- 组件可以派发(dispatch)行为(action)给store,而不是直接通知其它组件
- 其它组件可以通过订阅store中的状态(state)来刷新自己的视图
- 提供subscribe(),dispatch(),getState()方法
import rootReducer from "./reducers";
import {
createStore } from "redux";
import {
increase } from "./actions";
import * as actionTypes from './actionTypes'
const store = createStore(rootReducer);
//这两种都可以实现
store.dispatch({
type:actionTypes.INCREASE});
store.dispatch(increase())
console.log(store.getState())
export default store;
action
- action 是一个描述事件的简单对象,必须有一个叫type的参数定义action类型。它是改变 store 中 state 的唯一方法,它通过 store.dispatch() 方法来将 action 传到 store 中。
- 为每个 action 用纯函数编写 reducer 来描述如何修改 state 树
- (state 是只读的)唯一改变 state的方法就是触发 action,用户是接触不到state的,只能有view触发,所以,这个action可以理解为指令,需要发出多少动作就有多少指令
- action发出命令后将state放入reducer加工函数中,对state进行加工处理,返回新的state。
import {
createAction } from "redux-actions";
import * as actionTypes from "../actionTypes";
export const list = createAction(actionTypes.LIST);
export function increase() {
return {
type: actionTypes.INCREASE
};
}
export function reset() {
return {
type: actionTypes.RESET
};
}
export function decrease() {
return {
type: actionTypes.DECREASE
};
}
actionTypes
- 多数情况下, type 会被定义成字符串常量。当应用规模越来越大时,建议使用单独的模块或文件来存放 action。
export const INCREASE = "INCREASE";
export const DECREASE = "DECREASE";
export const RESET="RESET";
reducer
- 可以单独使用一个reducer,也可以将多个reducer合并成一个reducer,即:combineReducers()
- actions文件夹里存放是行为,而reducers文件夹存放的是具体的操作
- (使用纯函数来执行修改)reducer是一个纯函数,它接收初始值和action,描述action如何改变state tree,最后返回一个新的状态。
import {
handleActions } from "redux-actions";
import * as actionTypes from "../actionTypes";
import {
combineReducers } from "redux";
const initialState = {
list: {
},
count: 1
};
const list = handleActions(
{
[actionTypes.LIST]: (state, action) => {
return {
...state
};
}
//如果没有list,会变成三维数组
},
initialState.list
);
function reducers(state = initialState, action) {
switch (action.type) {
case actionTypes.INCREASE:
return {
count: state.count + 1
};
case actionTypes.DECREASE:
return {
count: state.count - 1
};
case actionTypes.RESET:
return {
count: 0
};
default:
//必须返回state
return state;
}
}
const rootReducer = combineReducers({
list,reducers
});
export default rootReducer;
PS:如果对我的代码和react项目感兴趣,欢迎clone我的react项目https://github.com/faimi/my-react