以下只是我对Redux的一些粗浅理解,用来理清逻辑思路
**Action (修改数据的标志 ),被dispatch带到reducers,根据标志做出判断,修改数据,更新getState,在监听器subscribe中,存放着执行函数,并且subscribe里面是自执行里面的函数,参数就是store.getState;每一次Action标志改变,都会修改此时的getState,重新渲染组件; **
一个简单的例子,手动实现redux过程:
/*初始数据:*/
const appState = {
title:{
text:'LG',
color:'#000'
},
content:{
text:'今年18',
color:'#00f'
}
}
/*
Reducers,它负责数据的修改。
action必须是一个对象,必须包含一个type字段,来说明你的目的;
你甚至可以认为此时的dispatch它就是一个中间件;
*/
function stateChange( prevState, action ){
switch (action.type){
case 'UPDATE_TITLE_TEXT':
prevState.title.text = action.text;
break;
case 'UPDATE_TITLE_COLOR':
prevState.title.color = action.color;
break;
default:
break;
}
}
/*
起store作用
state:表示状态;
stateChange,表示应用根据action发生什么变化
*/
function createStore( state, stateChange ){
const listeners = [];
const subscribe = ( listener ) => {
listeners.push(listener);//存放执行函数,由于执行函数的参数变化,引起组件的变化
// console.log(listeners.length)
};
const getState = state;
// console.log('初始state:'+getState.title.text);
const despatch = ( action ) => {
//console.log('调用despatch但没有修改state时:'+getState.title.text);
stateChange( state,action );
//console.log('修改之后的state:'+getState.title.text);
listeners.forEach((listener) => {
//自执行渲染组件的函数
// console.log("1")
listener()
});
//监听每次执行函数的参数变化,自执行渲染函数renderAPP
}
return { getState, despatch, subscribe }
}
//组件的执行函数
function renderApp( appState ){
renderTitle( appState.title );
renderContent( appState.content );
}
function renderTitle( title ){
const titleDOM = document.getElementById('title');
titleDOM.innerHTML = title.text;
titleDOM.style.color = title.color;
}
function renderContent( content ){
const contentDOM = document.getElementById('content');
contentDOM.innerHTML = content.text;
contentDOM.style.color = content.color;
}
const store = createStore( appState, stateChange );
renderApp( store.getState ); //第一次渲染页面
//console.log( store.getState )
// console.log( store.dispatch )
// console.log( store.subscribe )
//监听函数,把每次变化后的页面传过去放入listeners数组中,
//然后,自执行数组
store.subscribe(function(){
renderApp( store.getState );
});
//传递action
store.dispatch({
type:'UPDATE_TITLE_TEXT',
text:'LG被修改xxx'
});