Redux – React 基础代码

这是一个最简单最简单的Redux例子:

包括 Store, Reducer, Action.

 

import style from "./style.css";
import { createStore } from "redux";

const initialState = {
	name: 'Colin',
	age : 17
};

const rootReducer = (state = initialState, action) => {
	if(action.type == "add"){
		state = {...state, age:state.age+action.payload }
	}
	if(action.type == "minus"){
		state = {...state, age:state.age-action.payload }
	}
	return state;
}

const store = createStore(rootReducer);

store.subscribe(() => {
	console.log(store.getState());
});

console.log(store.getState());

store.dispatch({type:'add',payload:3});
store.dispatch({type:'add',payload:2});
store.dispatch({type:'add',payload:5});
store.dispatch({type:'minus',payload:4});