create-redux-action
安装
yarn add create-redux-action
// or
npm install --save create-redux-action
使用方式
命名方式
action最好使用驼峰命名法,书写为fetchBooks
,并且借助ts的类型提示自动补全。
Sync
Create a synchronous action to change visibility filter.
import { syncCreator } from 'create-redux-action';
export const sync = syncCreator({
prefix: 'users',
actions: ['setVisibilityFilter'],
});
import { sync } from './action.ts';
const {
setVisibilityFilter,
} = sync;
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onVisibilityFilterSet: (payload) => {
dispatch(setVisibilityFilter(payload));
},
};
};
import { sync } from './action.ts';
const { setVisibilityFilter } = sync;
const initialState = {
users: [{
id: '1',
name: 'Alice',
role: 'admin',
}, {
id: '2',
name: 'Bill',
role: 'seller',
}],
visibilityFilter: '',
};
export default function Reducer(state=initialState, action) {
switch(action.type) {
case setVisibilityFilter.TYPE:
return {
...state,
visibilityFilter: action.payload.role,
};
default:
return state;
}
}
Async
import { asyncCreator } from 'create-redux-action';
export const async = asyncCreator({
prefix: 'users',
actions: ['deleteUser'],
});
import { async } from './action.js';
const {
deleteUser,
} = async;
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onUserDelete: (payload) => {
dispatch(deleteUser(payload));
},
};
};
import { async } from './action.js';
const { deleteUser } = async;
const initialState = {
users: [{
id: '1',
name: 'Alice',
role: 'admin',
}, {
id: '2',
name: 'Bill',
role: 'seller',
}],
isLoading: false,
};
export default function Reducer(state=initialState, action) {
switch(action.type) {
case deleteUser.TYPE:
return {
...state,
isLoading: true,
};
case deleteUser.SUCCESS:
const id = action.payload.id;
return {
...state,
users: state.users.filter((user) => user.id !== id),
isLoading: false,
};
case deleteUser.FAILURE:
return {
...state,
isLoading: false,
};
default:
return state;
}
}
import { put, takeLatest } from 'redux-saga/effects';
import { async } from './action.ts';
const { deleteUser } = async;
function* deleteUserById(action) {
try {
const id = action.payload.id;
yield put(deleteUser.success({ id }));
} catch(err) {}
yield put(deleteUser.failure(err));
}
export default function* () {
yield takeLatest(deleteUser.TYPE, deleteUserById);
}
感谢
项目改进自于https://github.com/marcosun/redux-action-boilerplate.git
- 使用
typescript
改写项目,可自动推断出action的名称 - 由之前的构造函数方式,改进为函数创建的方式
- 去除过时的API