本文主要是介绍封装redux中的createStore,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
redux用于react中的状态管理,其中不能直接修改redux中的状态,需要通过dispatch方法才能修改react中的状态。
createStore函数中存放着状态信息state,它的执行结果返回一个store对象,返回的对象包含:
getState(获取store中的state状态信息,但是不能直接修改store中的state信息)
dispatch(修改store中的state信息)
subscribe(用于订阅事件)
<div>
<div id="title"></div>
<div id="content"></div>
</div>
<script>
function createStore(reducer) {
// 定义store对象中的状态信息对象,此处必须是只定义不赋值,因为这样在下面的dispatch初始化state时才能使用默认值初始化state
let state;
// listener是一个事件池,存储订阅的方法
let listener = [];
// 在createStore作用域下创建getState函数,该函数需要返回一个新对象,该对象需要和state一样。这个方法只用于获取state
// 深克隆:将当前作用域下的state深克隆一份,让外界利用这个方法只能获取state不能修改state
let getState = () => JSON.parse(JSON.stringify(state));
// 定义修改state的函数dispatch。action中的type一般是const大写的常量
function dispatch(action) {
state = reducer(state,action);
// 在dispatch中执行订阅的方法
listener.forEach((item,index)=>{
if(typeof item==="function"){
item();
}
});
}
// 这个函数的执行是在初始化state对象
dispatch({});
// 在createStore中有一个订阅方法subscribe,该函数返回取消订阅的函数
let subscribe = (fn)=>{
listener.push(fn);
// 返回取消订阅的方法,当返回值执行时就会取消该订阅
return ()=>{
listener = listener.filter(item=>item!==fn);
};
};
return {
getState, dispatch,subscribe
};
}
let initState = {
title: { color: 'red', text: '你好' },
content: { color: 'yellow', text: '中国' }
};
const CHANGE_TITLE_TEXT = "CHANGE_TITLE_TEXT";
const CHANGE_CONTENT_COLOR = "CHANGE_CONTENT_COLOR";
function reducer(state = initState, action) {
switch (action.type) {
case CHANGE_TITLE_TEXT:
// 当解构出现重名,后面覆盖前面
return { ...state, title: { ...state.title, text: action.text } };
case CHANGE_CONTENT_COLOR:
return { ...state, content: { ...state.content, color: action.color } };
default:
return state;
}
}
let store = createStore(reducer);
// 数据渲染title、content
function renderTile() {
let title = document.getElementById("title");
title.innerHTML = store.getState().title.text;
title.style.color = store.getState().title.color;
}
function renderContent() {
let content = document.getElementById("content");
content.innerHTML = store.getState().content.text;
content.style.color = store.getState().content.color;
}
function renderApp() {
renderTile();
renderContent();
}
renderApp();
// redux中规定,不能直接修改state中的数据,必须通过dispatch来修改state中的数据
let f = store.subscribe(renderApp);
// f();//这个方法执行就会取消订阅的方法
setTimeout(() => {
store.dispatch({ type: CHANGE_TITLE_TEXT, text: '加油' });
store.dispatch({ type: CHANGE_CONTENT_COLOR, color: 'black' });
// renderApp();
}, 3000);
</script>
————————————————
版权声明:本文为CSDN博主「fengyezi159」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010510187/article/details/101557187
这篇关于封装redux中的createStore的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!