redux-actions
Redux 常用辅助库
redux-actions
npm install --save redux-actions
import { createAction, handleAction, handleActions } from "redux-actions";
createAction(type, payloadCreator = Identity, ?metaCreator)
将一个
let increment = createAction("INCREMENT", (amount) => amount);
// same as
increment = createAction("INCREMENT");
expect(increment(42)).to.deep.equal({
type: "INCREMENT",
payload: 42,
});
如果传入的action.error
设置为true
const increment = createAction("INCREMENT");
const error = new TypeError("not a number");
expect(increment(error)).to.deep.equal({
type: "INCREMENT",
payload: error,
error: true,
});
handleAction(type, reducer | reducerMap, ?defaultState)
handleAction('FETCH_DATA', {
next(state, action) {...}
throw(state, action) {...}
});
第三个参数指向了默认的
handleActions(reducerMap, ?defaultState)
handleAction
函数创建多个
const reducer = handleActions(
{
INCREMENT: (state, action) => ({
counter: state.counter + action.payload,
}),
DECREMENT: (state, action) => ({
counter: state.counter - action.payload,
}),
},
{ counter: 0 }
);
reselect
import { createSelector } from "reselect";
const shopItemsSelector = (state) => state.shop.items;
const taxPercentSelector = (state) => state.shop.taxPercent;
const subtotalSelector = createSelector(shopItemsSelector, (items) =>
items.reduce((acc, item) => acc + item.value, 0)
);
const taxSelector = createSelector(
subtotalSelector,
taxPercentSelector,
(subtotal, taxPercent) => subtotal * (taxPercent / 100)
);
export const totalSelector = createSelector(
subtotalSelector,
taxSelector,
(subtotal, tax) => ({ total: subtotal + tax })
);
let exampleState = {
shop: {
taxPercent: 8,
items: [
{ name: "apple", value: 1.2 },
{ name: "orange", value: 0.95 },
],
},
};
console.log(subtotalSelector(exampleState)); // 2.15
console.log(taxSelector(exampleState)); // 0.172
console.log(totalSelector(exampleState)); // { total: 2.322 }