基本概念和API
redux:
商店:store,存放state的容器
状态:state,就是应用中需要使用的数据
动作:action,定义数据操作
通知:dispatch,发送操作请求
函数:reducer,处理数据的业务逻辑
首先创建商店(store)
// 得到一个数据容器:store
let store=Redux.createStore( fn );
console.dir(store);
Redux.createStore()可以传2个参数,一个是reducer函数用来处理state,后期对 state 的操作都是通过 reducer 来实现的。另一个是数据的初始值,存在store中。例:
var users = [
{username: '小涛', gender: '男'},
{username: '小红', gender: '女'}
];
let store=Redux.createStore( reducer,users )
简单介绍一下store
console.dir(store)可以看到store下面有很多方法
这里介绍前2个方法:
getState():从store里面拿到数据,用法:store.getState()
dispatch():操作数据并通知reducer(后面详细说用法)
dispatch 方法
如果需要修改数据,则需要通过 store对象的 dispatch 方法来实现
dispatch接收一个对象参数,该对象必须包含一个type属性,type就是操作类型说明
我们把dispatch传入的参数称为:action
store.dispatch({
type: 'ADD',
newValue: {username: '小李', gender: '男'}
});
reducer函数的介绍
//创建reducer函数
let reducer = (state, action)=>{
//state 是store里存的所有数据
//action 是View 发出的通知,表示 State 应该要发生变化了
//action 是一个对象。其中的type属性是必须的,表示 action 的名称。
//当我们调用createStore,reducer是首次调用,state没有值
switch (action.type) {
//这里的 case 'ADD' 是和store.dispatch定义的type是相同的。store.dispatch执行是会触发reducer函数的调用,reducer函数会找对应的action.type进行数据的处理、变化(增删改查等)
case 'ADD':
return [action.newValue, ...state];
default:
return state;
}
}
工作流程梳理
redux:
商店:store,存放state的容器
状态:state,就是应用中需要使用的数据
动作:action,定义数据操作
通知:dispatch,发送操作请求
函数:reducer,处理数据的业务逻辑
- 首先创建一个store用于存放数据 let store=Redux.createStore( reducer,state )
- 用户发出 Action store.dispatch(action);
- 然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。let reducer = (state, action) => {
switch (action.type) {
case ‘XX’:
return [action.newValue, …state];
default:
return state;
}
}
4.State 一旦有变化,Store 就会调用监听函数。设置监听函数
store.subscribe(listener);
listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。
function listerner() {
let newState = store.getState();
component.setState(newState);
}