Skip to content

Instantly share code, notes, and snippets.

@logzh
Last active April 7, 2016 05:17
Show Gist options
  • Save logzh/99a7053410bed6248e38 to your computer and use it in GitHub Desktop.
Save logzh/99a7053410bed6248e38 to your computer and use it in GitHub Desktop.
redux-demo
import { combineReducers, createStore } from 'redux'
var objectAssign = require('object-assign');
// Action
const ADD_CART = 'ADD_CART';
const SET_GOODS_COLLECT = 'SET_GOODS_COLLECT';
function addToCart(goods) {
return {
type: ADD_CART,
goods
};
}
function collectGoods() {
return {
type: SET_GOODS_COLLECT
};
}
// reducers
var initGoods = {"id": 123, "name": "星战正版机器人BB-8", isCollect: false};
function goods(state = initGoods, action) {
switch (action.type) {
case SET_GOODS_COLLECT:
return objectAssign({}, state, {isCollect: !state.isCollect});
default:
return state;
}
}
var initCarts = [];
function carts(state = initCarts, action) {//es6 特性
switch (action.type) {
case ADD_CART:
return [...state, action.goods];//es6 特性
default:
return state;
}
}
const rootReducer = combineReducers({
goods,
carts
});
let store = createStore(rootReducer);
console.log(store.getState());
store.dispatch(collectGoods());
console.log(store.getState());
store.dispatch(addToCart({"id": 124, "name": "星战正版机器人BB-8", isCollect: false}));
console.log(store.getState());
store.dispatch(addToCart({"id": 125, "name": "星战正版机器人BB-10", isCollect: false}));
console.log(store.getState());
@logzh
Copy link
Author

logzh commented Jan 15, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment