├── .nvmdrc ├── src ├── react-app-env.d.ts ├── mockjs.d.ts ├── features │ ├── counter │ │ ├── counterAPI.ts │ │ ├── Counter.module.css │ │ ├── Counter.tsx │ │ └── counterSlice.ts │ ├── mock │ │ └── todos.ts │ ├── todos │ │ ├── TodoList.module.css │ │ ├── TodoList.tsx │ │ └── todoSlice.ts │ └── sagas.ts ├── app │ ├── hooks.ts │ └── store.ts ├── index.tsx ├── index.css ├── App.tsx ├── AppRouter.tsx ├── App.css ├── Layout │ └── index.tsx └── logo.svg ├── public ├── favicon.ico ├── logo192.png ├── logo512.png ├── robots.txt ├── manifest.json └── index.html ├── .gitignore ├── tsconfig.json ├── package.json └── README.md /.nvmdrc: -------------------------------------------------------------------------------- 1 | 18.19.0 -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/mockjs.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'mockjs' { 2 | export default any; 3 | } 4 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dext7r/learn-redux/master/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dext7r/learn-redux/master/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dext7r/learn-redux/master/public/logo512.png -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/features/counter/counterAPI.ts: -------------------------------------------------------------------------------- 1 | // A mock function to mimic making an async request for data 2 | export function fetchCount(amount = 1) { 3 | return new Promise<{ data: number }>((resolve) => 4 | setTimeout(() => resolve({ data: amount }), 500) 5 | ); 6 | } 7 | -------------------------------------------------------------------------------- /src/features/mock/todos.ts: -------------------------------------------------------------------------------- 1 | import Mock from 'mockjs'; 2 | 3 | const mockData = Mock.mock({ 4 | 'list|5-10': [ 5 | { 6 | 'id|+1': 1, 7 | text: '@sentence(3, 5)', 8 | completed: '@boolean', 9 | }, 10 | ], 11 | }); 12 | 13 | export default mockData.list; 14 | -------------------------------------------------------------------------------- /src/app/hooks.ts: -------------------------------------------------------------------------------- 1 | import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; 2 | import type { RootState, AppDispatch } from './store'; 3 | 4 | // Use throughout your app instead of plain `useDispatch` and `useSelector` 5 | export const useAppDispatch = () => useDispatch(); 6 | export const useAppSelector: TypedUseSelectorHook = useSelector; 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { createRoot } from 'react-dom/client'; 2 | import { Provider } from 'react-redux'; 3 | import { store } from './app/store'; 4 | import './index.css'; 5 | import AppRouter from './AppRouter'; 6 | const container = document.getElementById('root')!; 7 | const root = createRoot(container); 8 | 9 | root.render( 10 | 11 | 12 | 13 | ); 14 | 15 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import { Counter } from './features/counter/Counter'; 4 | import TodoList from './features/todos/TodoList'; 5 | import './App.css'; 6 | function App() { 7 | return ( 8 |
9 |
10 | logo 11 | {/* */} 12 | 13 |
14 |
15 | ); 16 | } 17 | 18 | export default App; 19 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/AppRouter.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; 3 | import Layout from './Layout'; 4 | import TodoList from './features/todos/TodoList'; 5 | import { Counter } from './features/counter/Counter'; 6 | 7 | const AppRouter: React.FC = () => { 8 | return ( 9 | 10 | 11 | }> 12 | } /> 13 | } /> 14 | 15 | 16 | 17 | ); 18 | }; 19 | 20 | export default AppRouter; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-float infinite 3s ease-in-out; 13 | } 14 | } 15 | 16 | .App-header { 17 | min-height: 100vh; 18 | display: flex; 19 | flex-direction: column; 20 | align-items: center; 21 | justify-content: center; 22 | font-size: calc(10px + 2vmin); 23 | } 24 | 25 | .App-link { 26 | color: rgb(112, 76, 182); 27 | } 28 | 29 | @keyframes App-logo-float { 30 | 0% { 31 | transform: translateY(0); 32 | } 33 | 50% { 34 | transform: translateY(10px); 35 | } 36 | 100% { 37 | transform: translateY(0px); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Layout/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Link, Routes, Route } from "react-router-dom"; // 使用 Routes 和 Route 3 | import TodoList from "../features/todos/TodoList"; 4 | import { Counter } from "../features/counter/Counter"; 5 | 6 | const Layout: React.FC = () => { 7 | return ( 8 |
9 |
10 | 21 |
22 |
23 | 24 | } /> 25 | } /> 26 | 27 |
28 |
{/* Footer content */}
29 |
30 | ); 31 | }; 32 | 33 | export default Layout; 34 | -------------------------------------------------------------------------------- /src/features/todos/TodoList.module.css: -------------------------------------------------------------------------------- 1 | /* src/features/todos/TodoList.module.css */ 2 | .row { 3 | display: flex; 4 | align-items: center; 5 | margin-bottom: 10px; 6 | } 7 | 8 | .textbox { 9 | flex: 1; 10 | padding: 8px; 11 | margin-right: 10px; 12 | } 13 | 14 | .button { 15 | padding: 8px 16px; 16 | margin-right: 10px; 17 | background-color: #007bff; 18 | color: white; 19 | border: none; 20 | cursor: pointer; 21 | } 22 | 23 | .button:disabled { 24 | background-color: grey; 25 | color: white; 26 | } 27 | 28 | .list { 29 | list-style-type: none; 30 | padding: 0; 31 | } 32 | 33 | .listItem { 34 | display: flex; 35 | align-items: center; 36 | margin-bottom: 5px; 37 | } 38 | 39 | .listItem span { 40 | flex: 1; 41 | cursor: pointer; 42 | } 43 | 44 | .completed { 45 | text-decoration: line-through; 46 | color: grey; 47 | } -------------------------------------------------------------------------------- /src/features/sagas.ts: -------------------------------------------------------------------------------- 1 | import { put, takeEvery } from 'redux-saga/effects'; 2 | import { Todo, fetchTodosFailure, fetchTodosSuccess } from './todos/todoSlice'; 3 | 4 | // 模拟异步获取 todos 的函数 5 | const fetchTodosFromAPI = () => { 6 | return new Promise((resolve, reject) => { 7 | setTimeout(() => { 8 | // 这里假设从 API 获取到了 todos 数据 9 | const todos: Todo[] = [ 10 | { id: 1, text: 'Todo 1', completed: false }, 11 | { id: 2, text: 'Todo 2', completed: true }, 12 | ]; 13 | resolve(todos); 14 | }, 1000); 15 | }); 16 | }; 17 | 18 | // 处理获取 todos 的 saga 函数 19 | function* fetchTodosWorkerSaga(): Generator { 20 | try { 21 | const todos = yield fetchTodosFromAPI(); 22 | yield put(fetchTodosSuccess(todos)); 23 | } catch (error: any) { // 使用类型断言将 error 转换为 string 类型 24 | yield put(fetchTodosFailure(error as string)); 25 | } 26 | } 27 | 28 | // 监听获取 todos 的 action 29 | export function* watchFetchTodos() { 30 | yield takeEvery('todos/fetchTodos', fetchTodosWorkerSaga); 31 | } 32 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@reduxjs/toolkit": "^1.9.7", 7 | "@types/node": "^17.0.45", 8 | "@types/react": "^18.3.2", 9 | "@types/react-dom": "^18.3.0", 10 | "mockjs": "^1.1.0", 11 | "react": "^18.3.1", 12 | "react-dom": "^18.3.1", 13 | "react-redux": "^8.1.3", 14 | "react-router-dom": "^6.23.1", 15 | "react-scripts": "5.0.1", 16 | "redux-logger": "^3.0.6", 17 | "redux-saga": "^1.3.0", 18 | "typescript": "^4.9.5" 19 | }, 20 | "scripts": { 21 | "start": "react-scripts start", 22 | "build": "react-scripts build", 23 | "eject": "react-scripts eject" 24 | }, 25 | "eslintConfig": { 26 | "extends": [ 27 | "react-app" 28 | ] 29 | }, 30 | "browserslist": { 31 | "production": [ 32 | ">0.2%", 33 | "not dead", 34 | "not op_mini all" 35 | ], 36 | "development": [ 37 | "last 1 chrome version", 38 | "last 1 firefox version", 39 | "last 1 safari version" 40 | ] 41 | }, 42 | "devDependencies": { 43 | "@types/mockjs": "^1.0.10", 44 | "@types/redux-logger": "^3.0.13" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/app/store.ts: -------------------------------------------------------------------------------- 1 | import { configureStore, ThunkAction, Action, Middleware } from '@reduxjs/toolkit'; 2 | import counterReducer from '../features/counter/counterSlice'; 3 | import todoReducer from '../features/todos/todoSlice'; 4 | import logger from 'redux-logger' 5 | import createSagaMiddleware from 'redux-saga'; 6 | import { all } from 'redux-saga/effects'; 7 | import { watchFetchTodos } from '../features/sagas'; 8 | 9 | const isDevelopment = process.env.NODE_ENV === 'development'; 10 | 11 | // 创建 redux-saga 中间件实例 12 | const sagaMiddleware = createSagaMiddleware(); 13 | 14 | // 创建根 Saga 函数 15 | function* rootSaga() { 16 | // 在此处放置你的所有 saga 函数 17 | yield all([ 18 | watchFetchTodos(), 19 | ]); 20 | } 21 | 22 | export const store = configureStore({ 23 | reducer: { 24 | counter: counterReducer, 25 | todos: todoReducer, 26 | }, 27 | middleware: (getDefaultMiddleware) => { 28 | const middleware = getDefaultMiddleware(); 29 | if (isDevelopment) { 30 | middleware.push(logger as Middleware<{}, any, any>); 31 | } 32 | middleware.push(sagaMiddleware); 33 | return middleware; 34 | },}); 35 | 36 | // 运行根 Saga 函数 37 | sagaMiddleware.run(rootSaga); 38 | export type AppDispatch = typeof store.dispatch; 39 | export type RootState = ReturnType; 40 | export type AppThunk = ThunkAction< 41 | ReturnType, 42 | RootState, 43 | unknown, 44 | Action 45 | >; 46 | 47 | -------------------------------------------------------------------------------- /src/features/counter/Counter.module.css: -------------------------------------------------------------------------------- 1 | .row { 2 | display: flex; 3 | align-items: center; 4 | justify-content: center; 5 | } 6 | 7 | .row > button { 8 | margin-left: 4px; 9 | margin-right: 8px; 10 | } 11 | 12 | .row:not(:last-child) { 13 | margin-bottom: 16px; 14 | } 15 | 16 | .value { 17 | font-size: 78px; 18 | padding-left: 16px; 19 | padding-right: 16px; 20 | margin-top: 2px; 21 | font-family: 'Courier New', Courier, monospace; 22 | } 23 | 24 | .button { 25 | appearance: none; 26 | background: none; 27 | font-size: 32px; 28 | padding-left: 12px; 29 | padding-right: 12px; 30 | outline: none; 31 | border: 2px solid transparent; 32 | color: rgb(112, 76, 182); 33 | padding-bottom: 4px; 34 | cursor: pointer; 35 | background-color: rgba(112, 76, 182, 0.1); 36 | border-radius: 2px; 37 | transition: all 0.15s; 38 | } 39 | 40 | .textbox { 41 | font-size: 32px; 42 | padding: 2px; 43 | width: 64px; 44 | text-align: center; 45 | margin-right: 4px; 46 | } 47 | 48 | .button:hover, 49 | .button:focus { 50 | border: 2px solid rgba(112, 76, 182, 0.4); 51 | } 52 | 53 | .button:active { 54 | background-color: rgba(112, 76, 182, 0.2); 55 | } 56 | 57 | .asyncButton { 58 | composes: button; 59 | position: relative; 60 | } 61 | 62 | .asyncButton:after { 63 | content: ''; 64 | background-color: rgba(112, 76, 182, 0.15); 65 | display: block; 66 | position: absolute; 67 | width: 100%; 68 | height: 100%; 69 | left: 0; 70 | top: 0; 71 | opacity: 0; 72 | transition: width 1s linear, opacity 0.5s ease 1s; 73 | } 74 | 75 | .asyncButton:active:after { 76 | width: 0%; 77 | opacity: 1; 78 | transition: 0s; 79 | } 80 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React Redux App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/features/counter/Counter.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | 3 | import { useAppSelector, useAppDispatch } from '../../app/hooks'; 4 | import { 5 | decrement, 6 | increment, 7 | incrementByAmount, 8 | incrementAsync, 9 | incrementIfOdd, 10 | selectCount, 11 | } from './counterSlice'; 12 | import styles from './Counter.module.css'; 13 | 14 | export function Counter() { 15 | const count = useAppSelector(selectCount); 16 | const dispatch = useAppDispatch(); 17 | const [incrementAmount, setIncrementAmount] = useState('2'); 18 | 19 | const incrementValue = Number(incrementAmount) || 0; 20 | 21 | return ( 22 |
23 |
24 | 31 | {count} 32 | 39 |
40 |
41 | setIncrementAmount(e.target.value)} 46 | /> 47 | 53 | 59 | 65 |
66 |
67 | ); 68 | } 69 | -------------------------------------------------------------------------------- /src/features/todos/TodoList.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | import { useAppDispatch, useAppSelector } from "../../app/hooks"; 3 | import { 4 | Todo, 5 | addTodo, 6 | deleteTodo, 7 | selectTodos, 8 | toggleTodo, 9 | fetchTodos, 10 | } from "./todoSlice"; 11 | import styles from "./TodoList.module.css"; 12 | 13 | function TodoList() { 14 | const todos = useAppSelector(selectTodos); 15 | const dispatch = useAppDispatch(); 16 | const [text, setText] = useState(""); 17 | const isTextEmpty = text.trim() === ""; 18 | 19 | useEffect(() => { 20 | dispatch(fetchTodos()); 21 | }, [dispatch]); 22 | 23 | const handleAddTodo = () => { 24 | const trimmedText = text.trim(); 25 | if (trimmedText && !todos.find((todo) => todo.text === trimmedText)) { 26 | dispatch(addTodo(trimmedText)); 27 | setText(""); 28 | } else { 29 | alert(`已存在该项~`); 30 | setText(""); 31 | } 32 | }; 33 | 34 | return ( 35 |
36 |

Todo List

37 |
38 | setText(e.target.value)} 43 | /> 44 | 53 |
54 |
    55 | {todos.map((todo: Todo) => ( 56 |
  • 57 | dispatch(toggleTodo(todo.id))} 60 | > 61 | {todo.text} 62 | 63 | 69 |
  • 70 | ))} 71 |
72 |
73 | ); 74 | } 75 | export default TodoList; 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) TS template. 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /src/features/todos/todoSlice.ts: -------------------------------------------------------------------------------- 1 | import { createSlice, PayloadAction } from "@reduxjs/toolkit"; 2 | import { AppThunk } from "../../app/store"; 3 | import mockTodos from '../mock/todos'; 4 | 5 | export interface Todo { 6 | id: number; 7 | text: string; 8 | completed: boolean; 9 | } 10 | 11 | interface TodosState { 12 | list: Todo[]; 13 | loading: boolean; 14 | error: string | null; 15 | } 16 | 17 | const initialState: TodosState = { 18 | list: [], 19 | loading: false, 20 | error: null, 21 | }; 22 | 23 | export const todoSlice = createSlice({ 24 | name: "todos", 25 | initialState, 26 | reducers: { 27 | addTodo: (state, action: PayloadAction) => { 28 | const newTodo = { 29 | id: state.list.length ? state.list[state.list.length - 1].id + 1 : 1, 30 | text: action.payload, 31 | completed: false, 32 | }; 33 | state.list.push(newTodo); 34 | }, 35 | toggleTodo: (state, action: PayloadAction) => { 36 | const todo = state.list.find((todo) => todo.id === action.payload); 37 | if (todo) { 38 | todo.completed = !todo.completed; 39 | } 40 | }, 41 | deleteTodo: (state, action: PayloadAction) => { 42 | state.list = state.list.filter((todo) => todo.id !== action.payload); 43 | }, 44 | fetchTodosStart: (state) => { 45 | state.loading = true; 46 | state.error = null; 47 | }, 48 | fetchTodosSuccess: (state, action: PayloadAction) => { 49 | state.loading = false; 50 | state.error = null; 51 | state.list = action.payload; 52 | }, 53 | fetchTodosFailure: (state, action: PayloadAction) => { 54 | state.loading = false; 55 | state.error = action.payload; 56 | }, 57 | }, 58 | }); 59 | 60 | export const { addTodo, toggleTodo, deleteTodo, fetchTodosStart, fetchTodosSuccess, fetchTodosFailure } = todoSlice.actions; 61 | 62 | export const selectTodos = (state: { todos: TodosState }) => state.todos.list; 63 | 64 | export const fetchTodos = (): AppThunk => async (dispatch) => { 65 | dispatch(fetchTodosStart()); 66 | try { 67 | // 模拟异步请求 68 | setTimeout(() => { 69 | dispatch(fetchTodosSuccess(mockTodos)); 70 | }, 1000); 71 | } catch (error) { 72 | dispatch(fetchTodosFailure((error as Error).message)); 73 | } 74 | }; 75 | 76 | export default todoSlice.reducer; 77 | -------------------------------------------------------------------------------- /src/features/counter/counterSlice.ts: -------------------------------------------------------------------------------- 1 | import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'; 2 | import { RootState, AppThunk } from '../../app/store'; 3 | import { fetchCount } from './counterAPI'; 4 | 5 | export interface CounterState { 6 | value: number; 7 | status: 'idle' | 'loading' | 'failed'; 8 | } 9 | 10 | const initialState: CounterState = { 11 | value: 0, 12 | status: 'idle', 13 | }; 14 | 15 | // The function below is called a thunk and allows us to perform async logic. It 16 | // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This 17 | // will call the thunk with the `dispatch` function as the first argument. Async 18 | // code can then be executed and other actions can be dispatched. Thunks are 19 | // typically used to make async requests. 20 | export const incrementAsync = createAsyncThunk( 21 | 'counter/fetchCount', 22 | async (amount: number) => { 23 | const response = await fetchCount(amount); 24 | // The value we return becomes the `fulfilled` action payload 25 | return response.data; 26 | } 27 | ); 28 | 29 | export const counterSlice = createSlice({ 30 | name: 'counter', 31 | initialState, 32 | // The `reducers` field lets us define reducers and generate associated actions 33 | reducers: { 34 | increment: (state) => { 35 | // Redux Toolkit allows us to write "mutating" logic in reducers. It 36 | // doesn't actually mutate the state because it uses the Immer library, 37 | // which detects changes to a "draft state" and produces a brand new 38 | // immutable state based off those changes 39 | state.value += 1; 40 | }, 41 | decrement: (state) => { 42 | state.value -= 1; 43 | }, 44 | // Use the PayloadAction type to declare the contents of `action.payload` 45 | incrementByAmount: (state, action: PayloadAction) => { 46 | state.value += action.payload; 47 | }, 48 | }, 49 | // The `extraReducers` field lets the slice handle actions defined elsewhere, 50 | // including actions generated by createAsyncThunk or in other slices. 51 | extraReducers: (builder) => { 52 | builder 53 | .addCase(incrementAsync.pending, (state) => { 54 | state.status = 'loading'; 55 | }) 56 | .addCase(incrementAsync.fulfilled, (state, action) => { 57 | state.status = 'idle'; 58 | state.value += action.payload; 59 | }) 60 | .addCase(incrementAsync.rejected, (state) => { 61 | state.status = 'failed'; 62 | }); 63 | }, 64 | }); 65 | 66 | export const { increment, decrement, incrementByAmount } = counterSlice.actions; 67 | 68 | // The function below is called a selector and allows us to select a value from 69 | // the state. Selectors can also be defined inline where they're used instead of 70 | // in the slice file. For example: `useSelector((state: RootState) => state.counter.value)` 71 | export const selectCount = (state: RootState) => state.counter.value; 72 | 73 | // We can also write thunks by hand, which may contain both sync and async logic. 74 | // Here's an example of conditionally dispatching actions based on current state. 75 | export const incrementIfOdd = 76 | (amount: number): AppThunk => 77 | (dispatch, getState) => { 78 | const currentValue = selectCount(getState()); 79 | if (currentValue % 2 === 1) { 80 | dispatch(incrementByAmount(amount)); 81 | } 82 | }; 83 | 84 | export default counterSlice.reducer; 85 | --------------------------------------------------------------------------------