redux-sugar v1.1.0
REDUX-SUGAR
using redux easely, say goodbye to annoying action.type
, and put action
and reducer
in same scope, in order to better coding.
usage
install:
npm i --save redux-sugar
register, filename ./store.js
:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { registerStore } from 'redux-sugar';
const initialState = {};
const initialReducers = {};
const store = createStore(
combineReducers({ ...initialReducers }),
initialState,
applyMiddleware(
thunkMiddleware,
createLogger()
)
);
registerStore(store, initialReducers);
export { store };
transitions(actions
and reducers
), filename ./todoList.state.js
:
export default {
name: 'todo-list',
initialState: {
tasks: []
},
events: {
addTodo: {
action(title) {
const task = { title, completed: false };
return task;
},
reducer(state, task) {
state.tasks.push(task);
return state;
}
}
}
};
wrapped component ./TodoListComponent.jsx
:
import React from 'react';
import { connect } from 'react-redux';
import { sugarFactory } from 'redux-sugar';
import transitions from './todoList.state';
import { store } from './store';
class TodoListComponent extends Component {
...
addTodo(title) {
const { dispatch } = this.props;
dispatch(this.props.actions.addTodo(value))
}
...
}
const mapStateToProp = (state, ownProps) => {
var currentState = state[ownProps.reduxSugarId];
return { tasks: currentState.tasks };
};
const reduxSugarTodoListComponent = sugarFactory.react(store, transitions)(TodoListComponent);
const connectedTodoListComponent = connect(mapStateToProp)(reduxSugarTodoListComponent);
export { connectedTodoListComponent as TodoListComponent };
Tips
first, when coding the the transition, you will never care about the action.type
, just name your transition and put the action
and reducer
in the events
namespace. reducer will recive what the action
return in secode argument, first arguement is state
, just keep same to the redux official.
second, wrap your React Component with sugarFactory.react
, store
and transition
, it works when componentDidMount
and destroy when componentWillUnmount
.
in the wrapped component, reduxSugarId
and actions
will add to this.props
automatically. reduxSugarId
is the namespace in state, if you want to save the state, please try to put a unique reduxSugarId
for each component, especially the component has multiple instance at the same time. actions
is all the actionCreators of your transition, you can dispatch it, e.g.
this.props.dispatch(this.props.actions.addTodo('eating'))
The MIT License (MIT).
Written by qinyuanbin.