Redux核心运作流程

Redux的基本原则
Redux的基本原则
1.唯一数据源
应用的状态数据应该只存储在唯一的一个Store上,即State树。
2.保存状态只读
不能直接修改state的值,必须通过派发action对象完成。通过getState()获取值
3.数据改变只能通过纯函数
这里的纯函数就是reducer,函数的返回结果必须有两个参数state和action决定
createStore源码
export default function createStore(reducer, initialState) {
var currentReducer = reducer;
var currentState = initialState;
var listeners = [];
var isDispatching = false;
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
//根据自定义的reducer处理state和action,并返回新的state。同时触发listener的调用
function dispatch(action) {
try {
isDispatching = true;
//返回新的state
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
//触发listener调用
listeners.slice().forEach(listener => listener());
return action;
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
// Store初始化,会执行一次dispatch
dispatch({ type: ActionTypes.INIT });
return {
dispatch,
subscribe,
getState,
replaceReducer
};
}
描述
1.创建Store,持有一个State树(State Tree)
2.改变Store中的数据,唯一的方式就是调用dispatch()方法
3.应用中仅仅存在一个Store
4.指定状态树的不同部分应该如何响应动作(action)
5.通过使用combineReducers,将几个reducer合并成一个reducer函数
Redux的核心是一个store,这个store由Redux提供的createStore(reducers[,initialState])方法生成。要想生成store,必须传入reducers,第二个参数则可选
参数
- reducer
reducer是一个纯函数。给定当前state树和要处理的action的函数,返回新的state树。
reducer(previousState, action) => newState
- initialState 初始化状态。
关键方法
- getState()
获取store中当前的状态。 - dispatch(action)
分发一个action,并返回这个action。这是唯一能改变store中数据的方式,且触发listener的调用 - subscribe(listener)
注册一个监听者,它在store发生变化的时候被调用 - replaceReducer(nextReducer)
更新当前store里的reducer,一般只会在开发模式中调用该方法。
应用
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'
const store = createStore(counter)
const rootEl = document.getElementById('root')
const render = () => ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
rootEl
)
render()
store.subscribe(render)
本文介绍了Redux的基本原则,包括单一数据源、状态不可直接修改及数据变更仅通过纯函数实现等。详细解读了createStore源码,揭示了如何通过dispatch、getState和subscribe等方法管理状态。并展示了实际应用案例。
1108

被折叠的 条评论
为什么被折叠?



