使用 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-saga
yarn add redux-saga
# 安装 axios antd
yarn add axios antd
// store/index.ts
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
// 引入 redux-saga
import createSagaMiddleware from 'redux-saga'
import mySaga from './sagas';
import reducer from './reducer';
// redux-saga 中间件用法
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer, composeWithDevTools(applyMiddleware(sagaMiddleware)));
sagaMiddleware.run(mySaga);
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';
export const GET_LIST_SAGA = 'getListSaga';
// 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;
case GET_LIST_SAGA:
return newState;
default:
return state;
}
}
// store/action.ts
import { INPUT_VALUE, ADD_LIST, DELETE_LIST, GET_LIST, GET_LIST_SAGA } 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));
})
}
};
export const getTodoListSagaAction = () => ({
type: GET_LIST_SAGA
});
// store/sagas.ts
// eslint-disable-next-line
import { put, takeEvery, takeLatest } from 'redux-saga/effects';
import { GET_LIST_SAGA } from './actionTypes';
import { getListAction } from './action';
import axios from 'axios';
function* getListSaga() {
const res = yield axios.get('http://rap2.taobao.org:38080/app/mock/245836/dataList');
yield put(getListAction(res.data.list));
}
// 允许并发
function* mySaga() {
yield takeEvery(GET_LIST_SAGA, getListSaga)
}
// 不允许并发
// function* mySaga() {
// yield takeLatest(GET_LIST_SAGA, getListSaga);
// }
export default mySaga;