Redux的最基本样本代码(Immutable)

Redux其实就这样的一回事,十分的简单。

import { createStore } from "redux";

const initialState = {
	counter: 0
};

//Reducer
function reducer(state = initialState, action) {
	if (action.type === 'COUNT_UP') {
		//Mutable state(NO GOOD!)
		/*
		state.counter = state.counter + action.payload;
		return state;
		*/
		//Immutable state
		let newState = Object.assign({}, state);
		newState.counter = state.counter + action.payload;
		return newState;
	}
	return state;
};

//Action
function countUp(payload) {
  return { type: 'COUNT_UP', payload };
}

//Store
const store = createStore(reducer);

//Subscribe method accepts a callback that will fire whenever an action is dispatched.
const result = [];
store.subscribe(() => {
	result.push(store.getState());
	console.log(result);
})

console.log(store.getState());

//Dispatch
store.dispatch( countUp(1) );
store.dispatch( countUp(2) );
store.dispatch( countUp(3) );
store.dispatch( countUp(4) );
store.dispatch( countUp(5) );
store.dispatch( countUp(6) );

Output:

[ ]

[ { counter: 1 } ]

[ { counter: 1 }, { counter: 3 } ]

[ { counter: 1 }, { counter: 3 }, { counter: 6 } ]

[ { counter: 1 },
  { counter: 3 },
  { counter: 6 },
  { counter: 10 } ]

[ { counter: 1 },
  { counter: 3 },
  { counter: 6 },
  { counter: 10 },
  { counter: 15 } ]

[ { counter: 1 },
  { counter: 3 },
  { counter: 6 },
  { counter: 10 },
  { counter: 15 },
  { counter: 21 } ]

See?就这么的简单。

参考资料:
https://www.valentinog.com/blog/redux/