2016.12.13 The Piping System in ReactJS
-
Upload
szymon-kieloch -
Category
Documents
-
view
195 -
download
0
Transcript of 2016.12.13 The Piping System in ReactJS
● Define Reducer● Define Action Types
● Connect Reducer● Define Store● Define Action
● Use The Action● Connect Component To Store
export const GET_TASKS_LIST = 'get_tasks_list';export const UPDATE_TASK = 'update_task';export const DELETE_TASK = 'delete_task';
● Define Action Types
import { DELETE_TASK, GET_TASKS_LIST, UPDATE_TASK } from '../actions/types';
export default function (state = [], action) { switch (action.type) { case GET_TASKS_LIST: return action.payload;
case UPDATE_TASK: return ( state.map(task => { if (task.name === action.payload.name) { return action.payload; } return task; }) );
case DELETE_TASK: return state.filter(task => task.name !== action.payload.name);
default: return state; }}
● Define Reducer
import { combineReducers } from 'redux';import TasksReducer from './TasksReducer';
const rootReducer = combineReducers({ tasks: TasksReducer, // more reducers...});
export default rootReducer;
● Connect Reducers
import reducers from './reducers/rootReducer';
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);const store = createStoreWithMiddleware(reducers);
render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'));
● Define Store
import { GET_TASKS_LIST } from './types';import axios from 'axios';
export default function getTasks() { return dispatch => { axios.get('../tasks_list.json').then(response => { dispatch(getTasksAsync(response.data)); }); };}
function getTasksAsync(tasks) { return { type: GET_TASKS_LIST, payload: tasks, };}
● Define Actions
class App extends Component { componentDidMount() { this.props.getTasks(); }}
function mapDispatchToProps(dispatch) { return bindActionCreators({ getTasks: getTasks, }, dispatch);}
export default connect(null, mapDispatchToProps)(App);
● Use the Action
class TasksList extends Component { renderTasks() { if (!this.props.tasks) { return null; } return this.props.tasks.map(task => <Task key={task.name} task={task} /> ); }
render() { return ( <div> {this.renderTasks()} </div> ); } }
function mapStateToProps(state) { return { tasks: state.tasks }}
export default connect(mapStateToProps, null)(TasksList);
● Connect Component To Store