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 |
--------------------------------------------------------------------------------