
~~~
function renderApp(appState){
renderTitle(appState.title);
renderContent(appState.content);
}
function renderTitle(title){
let titleEle = document.getElementById('title');
titleEle.innerHTML = title.text;
titleEle.style.color = title.color;
}
function renderContent(content){
let contentEle = document.getElementById('content');
contentEle.innerHTML = content.text;
contentEle.style.color = content.color;
}
const UPDATE_TITLE_COLOR = 'UPDATE_TITLE_COLOR';
const UPDATE_TITLE_TEXT = 'UPDATE_TITLE_TEXT';
const UPDATE_CONTENT_COLOR = 'UPDATE_CONTENT_COLOR';
const UPDATE_CONTENT_TEXT = 'UPDATE_CONTENT_TEXT';
let initState ={
title:{
color:'red',
text:'標題'
},
content:{
color:'green',
text:'內容'
}
}
function reducer(state=initState,action){
//action就是一個普通對象,至少有一個屬性type 表示動作類型,表示你想對倉庫里的狀態干什么,另外其它的屬性任意給,沒有限制
switch(action.type){
case UPDATE_TITLE_COLOR:
return {...state,title:{...state.title,color:action.color}};
break;
case UPDATE_TITLE_TEXT:
return {...state,title:{...state.title,title:action.text}};
break;
case UPDATE_CONTENT_COLOR:
return {...state,content:{...state.content,color:action.color}};
break;
case UPDATE_CONTENT_TEXT:
return {...state,content:{...state.content,text:action.text}};
break;
default:
return state;
}
}
function createStore(reducer){
let state;
let listeners = [];
//負責返回當前的狀態
function getState(){
return state;
}
//我們可以派發一個動作,現在規定要想修改狀態,只能通過派發動作的方式來修改
function dispatch(action){
state = reducer(state,action);
listeners.forEach(l=>l());
}
//subscribe方法每次調用都會返回一個取消訂閱的方法
function subscribe(listener){
listeners.push(listener);
return function(){
listeners = listeners.filter(item=>item!==listener);
}
}
dispatch({type:"@@TYEP/REDUX_INIT"});
return {dispatch,getState,subscribe};
}
let store = createStore(reducer);
function render(){
renderApp(store.getState());
}
render();
let unsubscribe = store.subscribe(render);
setTimeout(() => {
store.dispatch({type:UPDATE_TITLE_COLOR,color:'purple'});
unsubscribe();
store.dispatch({type:UPDATE_CONTENT_TEXT,text:'新內容'});
}, 1000);
~~~