React redux配置 使用react-redux redux-thunk 实现todolist (一)

使用 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));
      })
  }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值