使用 redux 进行统一状态管理,实现 todolist 功能

# 安装 redux react-redux
yarn add redux react-redux @types/react-redux

# 安装 redux-devtools-extension
yarn add redux-devtools-extension @types/redux-devtools-extension

# 安装 redux-thunk
yarn add redux-thunk

# 安装 axios antd
yarn add axios antd
// store/index.ts
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
// 引入 redux-thunk
import thunk from 'redux-thunk';
import reducer from './reducer';

const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)));

export default store;
// store/actionTypes.ts
export const INPUT_VALUE = 'inputVale';
export const ADD_LIST = 'addList';
export const DELETE_LIST = 'deleteList';
export const GET_LIST = 'getList';
// store/reducer.ts
import { INPUT_VALUE, ADD_LIST, DELETE_LIST, GET_LIST, GET_LIST_SAGA } from './actionTypes';

const initState = {
  inputValue: 'Write Something',
  list: []
};

type IAction = {
  type: string,
  value?: any
}

export default (state = initState, action: IAction) => {
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type) {
    case INPUT_VALUE:
      newState.inputValue = action.value;
      return newState;
    case ADD_LIST:
      newState.list = [...newState.list, newState.inputValue];
      newState.inputValue = '';
      return newState;
    case DELETE_LIST:
      newState.list.splice(action.value, 1);
      return newState;
    case GET_LIST:
      newState.list = action.value;
      return newState;
    default:
      return state;
  }
}
// store/action.ts
import { INPUT_VALUE, ADD_LIST, DELETE_LIST, GET_LIST } from './actionTypes';
import axios from 'axios';

export const inputValueAction = (value) => ({ type: INPUT_VALUE, value });
export const addListAction = () => ({ type: ADD_LIST });
export const deleteListAction = (value) => ({ type: DELETE_LIST, value });
export const getListAction = (value) => ({ type: GET_LIST, value });

export const getTodoListThunkAction = () => {
  return (dispatch) => {
    axios.get('http://rap2.taobao.org:38080/app/mock/245836/dataList')
      .then(res => {
        dispatch(getListAction(res.data.list));
      })
  }
};

版权声明:本文为BradyCC原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/BradyCC/article/details/104649104