欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实现Redux的代码教程

程序员文章站 2022-09-11 09:18:44
实现Redux 'use stirct'; const EventEmitter = require('events').EventEmi...

实现Redux

'use stirct'; 
const EventEmitter = require('events').EventEmitter;
class Store{
	
	constructor(state){
		this._state = state || {};
		this._updates = {};
		this._emitter = new EventEmitter();
	}
	
	get state(){
		return JSON.parse(JSON.stringify(this._state));
	}
	
	setUpdates(fns){
		this._updates = fns;
	}
	
	dispatch(action){
		this._state = this._updates(this.state,action);
		this._emitter.emit('change');
	}
	listen(listener){
		this._emitter.on('change',listener)
	}
}

const sto = new Store({num:5});
sto.setUpdates(function(oldState,action){
	let newstate = {};
		switch(action.type){
			case '+':
				newstate.num = ++oldState.num;
				return newstate;
			case '+':
				newstate.num = ++oldState.num;
				return newstate;
			default:
				return oldState;
	}
})
sto.listen(()=>{
	console.log(sto.state)
})
const action = {
	type:'+'
};
sto.dispatch(action);

实现Redux:

'use stirct'; 
const EventEmitter = require('events').EventEmitter;
class Store{
	
	constructor(state){
		this._state = state || {};
		this._updates = {};
		this._emitter = new EventEmitter();
	}
	
	get state(){
		return JSON.parse(JSON.stringify(this._state));
	}
	
	setUpdates(fns){
		this._updates = fns;
	}
	
	dispatch(action){
		if(typeof this._updates === 'function'){
			this._state = this._updates(this.state,action);
		}else{
			let newState = {};
			const keys = Object.keys(this._updates);
			keys.forEach(key=>{
				let updater = this._updates[key];
				let value = this.state[key];
				let newSubState = updater(value,action);
				newState[key] = newSubState;
			});
			this._state = Object.assign({},this.state,newState);
		}
		this._emitter.emit('change');
	}
	listen(listener){
		this._emitter.on('change',listener)
	}
}

const sto = new Store({name:'Jack',num:5});
function numUpdater(oldNum,action){
		switch(action.type){
			case '+':
				return ++oldNum;
			case '-':
				return --oldNum;
			default:
				return oldNum;
	}
}
function nameUpdater(oldName,action){
	if(action.type ==='changeName'){
		return action.name;
	}else{
		return oldName
	}
	
}
sto.setUpdates({
	name:nameUpdater,
	num: numUpdater
});
sto.listen(()=>{
	console.log(sto.state)
})
const action = {
	type:'changeName',
	name:'Tom'
};
sto.dispatch(action);

实现Redux: