【每日一题】说下你对Redux的理解

人生苦短,总需要一点仪式感。比如学前端~
Redux
目录:
分析
Redux 三大原则
Redux 原理
Redux 工作流程
分析
在 jQuery 时代的时候,我们是面向过程开发。随着 react 的普及,我们提出状态驱动 UI 的开发模式。
我们认为:Web 应用就是状态与 UI 一一对应的关系。但是随着我们的 web 应用日趋的复杂化,一个应用所对应的背后的 state 也变得越来越难以管理。而 redux 就是 web 应用的一个状态管理方案。Redux 是 Flux 思想的一种实现,同时又在其基础上做了改进。其主要体现在:
单向数据流
Store 是唯一的数据源
Redux 三大原则
单一数据源
State 只读
使用纯函数来修改
Redux 原理
Redux 源码主要分为几个模块文件:
compose.js提供从右到左进行函数式编程
createStore.js提供作为生成唯一 store 的函数
combineReducers.js提供合并多个 reducer 的函数,保证 store 的唯一性
bindActionCreators.js可以让开发者在不直接接触 dispatch 的前提下进行更改 state 的操作
applyMiddleware.js这个方法可以通过中间件来增强 dispatch 的功能
const actionTypes = {
ADD: 'ADD',
CHANGEINFO: 'CHANGEINFO',
}
const initState = {
info: '初始化',
}
export default function initReducer(state=initState, action) {
switch(action.type) {
case actionTypes.CHANGEINFO:
return {
...state,
info: action.preload.info || '',
}
default:
return { ...state };
}
}
export default function createStore(reducer, initialState, middleFunc) {
if (initialState && typeof initialState === 'function') {
middleFunc = initialState;
initialState = undefined;
}
let currentState = initialState;
const listeners = [];
if (middleFunc && typeof middleFunc === 'function') {
// 封装dispatch
return middleFunc(createStore)(reducer, initialState);
}
const getState = () => {
return currentState;
}
const dispatch = (action) => {
currentState = reducer(currentState, action);
listeners.forEach(listener => {
listener();
})
}
const subscribe = (listener) => {
listeners.push(listener);
}
return {
getState,
dispatch,
subscribe
}
}
Redux 工作流程
const store = createStore(fn)生成数据;
action:{ type:Symbol('action001'), payload:'payload1' }定义行为;
dispatch发起 action:store.dispatch(doSomethingfn('action001'));
reducer处理 action,返回新的 state;
换句话解释是:
首先,用户(通过 view)发出action,发出方式用到了dispatch方法
然后,store 自动调用reducer,并且传入两个参数:当前 state 和收到的 action,reducer 会返回新的state
state 一旦有变化,store就会调用监听函数,来更新view。
所有《每日一题》的 知识大纲索引脑图 整理在此:https://www.yuque.com/dfe_evernote/interview/everyday
你也可以点击文末的 “阅读原文” 快速跳转

END
愿你历尽千帆,归来仍是少年。
让我们一起携手同走前端路!
关注公众号回复【加群】即可
评论
