个人redux学习整理,redux基础用法;
#### Redux
1. store:
全局唯一,保存数据的地方,你可以看作一个容器;
redux提供了createStore函数,用来生成store;
eg: import { createStore } from 'redux'; //引入
const store = createStore(reducer); //创建一个redux store ,包含您创建的reducer;
2. State:
store保存了所有数据,当你想要拿到某个时刻的数据,就要对state生成一个快照,这个时刻的数据集就叫state,
可以通过store.getState()获取到;
eg: const states = store.getState();
3. Action && dispatch:
state和view是一一对应的,当state的值改变了view就有相应的变化,反之,state的变化也是view发起的,当
用户触发action改变state值时候,view就有了相应的变化;
Action是一个对象,type是必须字段;其他参数是自定义的;
dispatch接受一个Action对象作为参数,发送出去;
eg: let action = { type: 'add' , value: 1 }; store.dispatch(action);
4. Action Creater
当view有多个操作的时候,就有多个Action的产生,每次都手写就会很麻烦,可以定义一个函数来生成Action,这就是Action Creater;
const type = 'add';
function addAction(text){
return {
type:type,
text //注意这里是es6缩写, es5对应位:text:text
}
};
const action = addAction('learn Redux');
5. Reducer
Store收到action之后,必须返回一个新的State,这样View才会发生改变;这种计算过程就叫Reducer;
Reducer是一个函数,它接受action和当前state作为参数,返回一个新的state;
eg:
let defaultState = 'test'; //初始化定义state,可以为您想的任何值,例如对象/数组/变量等;
const reducer = (state = defaultState , action) => { //将定义的值赋值给state,结合dispatch传递的action作为参数传递给reducer;
switch(action.type){ //根据action传递的type做出不同的处理函数;
case 'add': .... break;
return state; //返回修改后的state;
}
}
6. Reducer combineReducers
Redux提供了一个combineReducers方法,用于Reducer的拆分。你只要定义各个子Reducer函数,然后用这个方法,将她们合成一个大的Reducer。
const reducer = combineReducers({
a: doSomethingWithA, // 或者采用es6的写法 比如state属性名和Reducer同名;
b: processB,
c: c
})
// 等同于
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}

浙公网安备 33010602011771号