redux,react-redux ,react-thunk
redux: {creatStore,applyMiddleware,bindActionCreators};
react-redux: {provider,connect};
react-thunk:thunk
web应用是一个状态机,视图与状态一一对应;
全部的状态保存在一个对象中;
Store保存数据的地方,是一个状态的容器,整个应用只能有一个Store。
3.1 Store
3.2 state
3.3 Action:Action 描述当前发生的事情。改变 State 的惟一办法,就是使用 Action。它会运送数据到 Store。
3.4 Action creator :View 要发送多少种消息,就会有多少种 Action。若是都手写,会很麻烦。能够定义一个函数来生成 Action,这个函数就叫 Action Creator。
const ADD_TODO = ‘添加toDo'
function addToDo(text) {
return {
todo: ADD_TODO,
text
}
}
const action = addToDo(‘learning redux’);//addToDo就是ActionCreator
3.5 store.dispatch():
store.dispatch()
是 View 发出 Action 的惟一方法。
import React from ‘react’;
import React-dom from ‘react-dom’;
import {createStore} from ‘redux’;
const store = ctreateStore(fn);
store.dispatch({
type: ‘ADD_TODO’,
payLoad: ‘learning English'
})
or.
store.dispatch(addToDo(‘learning hello’);
3.6 Reducer
Store 收到 Action 之后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫作 Reducer。react
Reducer 是一个函数,它接受 Action 和当前 State 做为参数,返回一个新的 State。web
const reducer = function (state,action) {redux
return new_state;服务器
}
app
const defaultState = 0; dom
const reducer = (state = defaultState,action)=> { ide
switch(action.type) {函数
case ADD_ToDo: spa
return state+action.payload;code
default:
return state;
}
}
const state = reducer(1,{
type: ADD,
payload: ‘learning redux'
})
2、Store的实现
getState(),dispatch,subscribe()
import {createStore} from ‘redux’;
{getState,dispatch,subscribe} = createStore(reducer);
createStore
方法还能够接受第二个参数,表示 State 的最初状态。这一般是服务器给出的。
let store = createStore(todoApp, window.STATE_FROM_SERVER)
3、reducer的分拆与合并
import {combineReducer} from ‘redux’;
合并三个子Reducer;
chatReducer =combineReducer({
chatLog,
statusMsg,
userInfo
}) ;
const reducer = combineReducer({
a: doSomethingWithA,
b: processb,
c: c
});
等价于:
const reducer = function(state = defaultState,action)=> {
return {
a: doSomethingWithA(state.a,action),
b: processB(state.b,action),
c: c(state.c,actioin)
}
}
总之,
combineReducers()
作的就是产生一个总体的 Reducer 函数。
一个模拟combineReducer的简单的实现;
const reducer = (nextState,key) => {
nextStae[key] = reducers[key](state[key],action);
return nextState;
}
const combineReducer = reducers => {
return ( state={}, action) => {
return Object.keys(reducers).reduce((nextState,key) =>{
nextState[key] = reducers[key](state[key],action);
return nextState;
},{})
})
}
Redux:
creatStore:redux生成Store的方法;
import {createStore} from ‘redux’;
const store = createStore(reducer);
const state = store.getState();