当前位置: 移动技术网 > IT编程>网页制作>CSS > 实现Redux的代码教程

实现Redux的代码教程

2018年03月28日  | 移动技术网IT编程  | 我要评论

实现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:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网