Redux的使用步骤
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。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
const reducer = function (state,action) {
return new_state;
}
const defaultState = 0;
const reducer = (state = defaultState,action)=> {
switch(action.type) {
case ADD_ToDo:
return state+action.payload;
default:
return state;
}
}
const state = reducer(1,{
type: ADD,
payload: ‘learning redux'
})
二、Store的实现
getState(),dispatch,subscribe()
import {createStore} from ‘redux’;
{getState,dispatch,subscribe} = createStore(reducer);
createStore方法还可以接受第二个参数,表示 State 的最初状态。这通常是服务器给出的。let store = createStore(todoApp, window.STATE_FROM_SERVER)
三、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();

浙公网安备 33010602011771号