美文网首页
React-todo-list 系列七

React-todo-list 系列七

作者: Mark同学 | 来源:发表于2019-12-11 09:30 被阅读0次

    React-Redux => ImmutableJS

    store
    ——reducer.js

    import * as constants from './constants';
    import { fromJS } from 'immutable';
    
    const defaultState = fromJS({
      list: [],
      inputValue: ''
    })
    
    export default (state = defaultState, action) => {
      if (action.type === constants.INIT_TODO_LIST) {
        return state.set('list', action.value)
      }
    
      if (action.type === constants.CHANGE_INPUT_VALUE) {
        return state.set('inputValue', action.value)
      }
    
      if (action.type === constants.ADD_TODO_ITEM) {
        return state.merge({
          list: state.get('list').concat(state.get('inputValue')),
          inputValue: ''
        })
      }
    
      if (action.type === constants.DELETE_TODO_ITEM) {
        return state.set('list', state.get('list').splice(action.value, 1))
      }
      return state
    }
    

    store
    ——actionCreators.js

    import * as constants from './constants'
    import axios from 'axios'
    import { fromJS } from 'immutable';
    
    export const getInputChangedAction = (value) => ({
      type: constants.CHANGE_INPUT_VALUE,
      value: fromJS(value)
    })
    
    export const getTodoAddedAction = () => ({
      type: constants.ADD_TODO_ITEM
    })
    
    export const getTodoDeletedAction = (value) => ({
      type: constants.DELETE_TODO_ITEM,
      value: fromJS(value)
    })
    
    export const initTodoListAction = (value) => ({
      type: constants.INIT_TODO_LIST,
      value: fromJS(value)
    })
    
    export const getTodoList = () => {
      return (dispatch) => {
        axios.get('/api/todo.json').then((res) => {
          const result = res.data.data;
          dispatch(initTodoListAction(result.list))
        })
      }
    }
    

    TodoList.js

    const mapStateToProps = (state) => {
      return {
        list: state.get('list'),
        inputValue: state.get('inputValue')
      }
    }
    

    相关文章

      网友评论

          本文标题:React-todo-list 系列七

          本文链接:https://www.haomeiwen.com/subject/fsxogctx.html