/*views/TodoList/indexRedux.js*/ const taskListData = { loading: true, error: false, taskList: [] }; //不同的action; const LOAD_TASKLIST = 'LOAD_TASKLIST'; const LOAD_TASKLIST_SUCCESS = 'LOAD_TASKLIST_SUCCESS'; const LOAD_TASKLIST_ERROR = 'LOAD_TASKLIST_ERROR'; const ADD_TASK = 'ADD_TASK'; const UPDATE_TASK = 'UPDATE_TASK'; const DELETE_TASK = 'DELETE_TASK'; function todoListReducer (state = { taskListData }, action) { switch(action.type) { case LOAD_TASKLIST: { return { ...state, loading: true, error: false, } } case LOAD_TASKLIST_SUCCESS: { return { ...state, loading: false, error: false, taskList: action.payload, }; } case LOAD_TASKLIST_ERROR: { return { ...state, loading: false, error: true }; } case UPDATE_TASK: { const index = state.taskList.indexOf( state.taskList.find(task => task.id === action.payload.id)); console.log(index); state.taskList[index].status = !state.taskList[index].status; return { ...state, taskList: state.taskList, }; } case DELETE_TASK: { const index = state.taskList.indexOf( state.taskList.find(task => task.id === action.payload.id)); state.taskList.splice(index, 1); return { ...state, taskList: state.taskList, }; } case ADD_TASK: { let len = state.taskList.length; let index = len > 0 ? len - 1 : 0; let lastTaskId = index !== 0 ? state.taskList[index].id : 0; state.taskList.push({ id: lastTaskId + 1, name: action.payload.name, status: false, }); return { ...state, taskList: state.taskList, } } default: { return state; } } } export default todoListReducer;
3. action creator的分布:
每个动作都代表一个action,action由组件发出,所以将action creator单独一个文件,放在组件目录中。例如:ListItem组件的action creator:
/*ListItem/indexRedux.js*/ //处理更新任务状态后和删除任务后的taskList的状态; const UPDATE_TASK = 'UPDATE_TASK'; const DELETE_TASK = 'DELETE_TASK'; //action creator,更新和删除任务 export function updateTask (task) { return dispatch => { dispatch({ type: UPDATE_TASK, payload: task, }); } } export function deleteTask (task) { return dispatch => { dispatch({ type: DELETE_TASK, payload: task, }); } }
三. 如何将redux和组件连接
react-redux提供了connect方法,将state和action creator绑在组件上,然后在组价内部以props的方式获取。下面是TodoList页面的具体实现:
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import List from '../../component/List'; import { loadTaskList } from '../../component/List/indexRedux'; import { updateTask, deleteTask } from '../../component/ListItem/indexRedux'; import { addTask } from '../../component/SubmitDialog/indexRedux'; class TodoList extends Component { render () { return ( <List {...this.props} /> ); } } export default connect( state => { return { loading: state.taskListData.loading, error: state.taskListData.error, taskList: state.taskListData.taskList, }; }, dispatch => { return { loadTaskList: bindActionCreators(loadTaskList, dispatch), updateTask: bindActionCreators(updateTask, dispatch), deleteTask: bindActionCreators(deleteTask, dispatch), addTask: bindActionCreators(addTask, dispatch), }; })(TodoList);
内容版权声明:除非注明,否则皆为本站原创文章。