Detailed explanation of React-Redux

Detailed explanation of React-Redux

react-redux

foreword

React-Redux is a third-party library for managing state in React applications. It is based on the Redux architecture and provides a way to efficiently manage state in React applications. React-Redux makes it easier and more convenient to use Redux in React applications by combining the core concepts of Redux with React components.

  • An overview of React-Redux

React-Redux is a third-party library for managing state in React applications. It is based on the Redux architecture and provides a way to efficiently manage state in React applications. React-Redux makes it easier and more convenient to use Redux in React applications by combining the core concepts of Redux with React components.

The role of React-Redux is to help React applications better manage state. In React applications, state sharing and passing between components can become complex and confusing. As the application scale grows, state management becomes more difficult. React-Redux helps developers better manage state in React applications by providing a unified and predictable state management solution.

Managing state in a React application is very important. The application state includes user input, application data, UI state, etc. Good state management can improve the maintainability, scalability and testability of the application, and it can also reduce the errors and bugs in the application.

React-Redux, as a state management library, can help solve state management problems in React applications. By using some core concepts of Redux, such as single source of truth, immutability, and pure functions, React-Redux can provide a reliable way to manage the state of the application. It can help developers better organize and manage the state of the application, and provides a predictable state management solution, thereby reducing confusion and errors in state management.

By using React-Redux, developers can manage state more efficiently in React applications, improving application performance, maintainability, and scalability. React-Redux provides an elegant solution for the state management of React applications, enabling developers to focus more on the business logic and user experience of the application.

  • Why do you need React-Redux

State management is a key issue in React applications. As applications grow in size and complexity, state sharing and passing between components can become very complex. React itself provides some ways to handle the internal state of components, such as using component state and props. However, this approach can lead to confusing and difficult to maintain state management when the application becomes complex.

State sharing and passing between components is a common problem in React applications. State management becomes complicated when multiple components need to access and modify the same data. Components may need to pass multiple layers through props, or use callback functions to pass state and handle state changes. Such an approach may lead to increased coupling between components, and the code becomes difficult to understand and maintain.

As a state management library, Redux provides a solution to the state management problem in React applications. Redux takes a single source of truth and immutability approach to managing state by using pure functions to handle state changes. This approach makes state management more reliable and predictable, reducing the complexity of state management.

Redux also has some advantages and applicable scenarios. For example, Redux provides a centralized state management method that makes state changes and debugging easier. Redux can also be integrated with other middleware and tool libraries, such as Redux Thunk or Redux Saga, thus providing a richer and more flexible state management solution.

React-Redux, as the official binding library for using Redux in React applications, provides a simple and powerful way to integrate Redux into React applications. React-Redux offers several advantages that make it the best choice for using Redux in React applications. For example, React-Redux provides a way to tightly integrate with React components, making state access and modification more intuitive and convenient. React-Redux also provides some performance optimizations, such as using the connect function to avoid unnecessary component rendering.

The core concepts of Redux

react+redux

Redux is a state management library based on the Flux architecture, which introduces some core concepts to manage the state of the application. Understanding these core concepts is key to understanding React-Redux.

  • Basic principles and design ideas of Redux architecture

State management: Redux is a state management library for managing global state in React applications. Its core idea is to centrally store the state of the application in a global Store, making state changes traceable, controllable, and predictable.
Single source of data: Redux advocates the use of a single source of data to manage the state of the application, that is, the state of the entire application is stored in a global JavaScript object. This helps simplify the logic of state management, making state changes predictable and easy to debug.
Immutability: The state of Redux is immutable, that is, the state cannot be modified once created. Every time the state changes, a new state object is generated instead of directly modifying the original state. This helps avoid inconsistent state and hard-to-trace bugs.

  • Core concept
    Action (action): Action is a simple JavaScript object used to describe state changes in the application. It contains a type attribute, indicating the type of Action, and an optional payload attribute, used to carry the data of the Action. Action is used to describe an event or user behavior in the application, such as clicking a button, sending a network request, and so on.

Reducer: Reducer is a pure function that receives a current state and an Action as parameters and returns a new state. The main function of Reducer is to process the state change logic according to the type of Action. Whenever an Action is dispatched, Redux will call all registered Reducers, let them process the Action in turn, and return a new state.

Store (warehouse): Store is the core object of Redux, which is used to store the state of the entire application. It is the single source of truth where all state is stored. Create a Store through Redux's createStore function and pass in a Reducer to initialize the state. Store provides the getState() method to obtain the current state, the dispatch(action) method to dispatch an Action, and the subscribe(listener) method to register a listener and execute a callback function when the state changes.

  1. Action (action)
    Action is a simple JavaScript object used to describe a state change in the application. It contains a type field, indicating the type of the Action, and some optional payload fields, used to carry data. Action is used to describe events or user operations in the application, such as button clicks, data loading, etc.

Why do you need Actions? Actions provide a standardized and predictable way to describe state changes in an application. By using Actions, we can clearly define the state changes that may occur in the application, and can easily track state changes. In React-Redux, we can use Actions to trigger state changes.

How to create and dispatch Action? We can use ordinary JavaScript objects to create Actions, for example:

const increaseCounter = () => {
    
    
  return {
    
    
    type: 'INCREASE_COUNTER'
  }
}

Then, we can use the dispatch function provided by the Redux store to dispatch Actions, for example:

store.dispatch(increaseCounter());

  1. Reducer (state handler function)
    Reducer is a pure function used to handle state changes in the application. Reducer receives an old state and an Action, and then returns a new state according to the type and payload of the Action. A Reducer should be a pure function, i.e. it should not have any side effects and should not modify the parameters passed in.

Why do you need Reducers? Reducers provide a predictable and immutable way to handle state changes. By using Reducer, we can centrally manage the state change logic of the application, and can easily test and debug the state change process.

How to create and process Reducer? We can create Reducers using pure functions, for example:

const counterReducer = (state = 0, action) => {
    
    
  switch (action.type) {
    
    
    case 'INCREASE_COUNTER':
      return state + 1;
    case 'DECREASE_COUNTER':
      return state - 1;
    default:
      return state;
  }
}

Then, we can pass the Reducer into Redux's combineReducers function, and combine multiple Reducers into a root Reducer to manage the state of the entire application.

  1. Store (state storage)
    Store is the core object in Redux, which is used to store the state of the application. A Redux application can only have one Store, which is an object that contains the state of the entire application. Store provides several methods to manage state, including getState, dispatch, and subscribe.

Why do you need a store? The Store provides a centralized and controlled way to manage application state. By using a Store, we can store the state of the entire application in one place, and the state can be accessed and modified from anywhere in the application.

How to create and use Store? We can use the createStore function provided by Redux to create a Store, for example:

import {
    
     createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

In the above example, we used Redux's createStore function to create a Store and passed in a root Reducer. The root Reducer is composed of multiple Reducers through the combineReducers function.

Once the Store is created, we can use store.getState() to get the current state, use store.dispatch(action) to dispatch an Action to trigger a state change, and use store.subscribe(listener) to register a listener , the callback function is executed when the state changes.

  • Redux's single source of truth and immutability

Redux's single data source and immutability are two important design ideas of Redux. A single source of truth makes state management simple and predictable, while immutability ensures state stability and traceability. In React-Redux, these features make state management in React applications more efficient and easier to maintain. Understanding these core concepts is very important for a deep understanding of the usage and principles of React-Redux. In the next section, we'll dive into how to use React-Redux for state management in React applications.

Redux workflow

react+redux

  • The workflow of Redux can be simply summarized as the following steps:
  1. Trigger Action: An event or user behavior in the application triggers an Action. An Action is an ordinary JavaScript object containing a type attribute and an optional payload attribute, which is used to describe a state change.
  2. Dispatch Action: Dispatch Action to Redux Store by calling Redux's dispatch(action) method.
  3. Process the Reducer: After the Store receives the Action, it will call all registered Reducer functions, and pass the current state and Action into the Reducer.
  4. Update state: Reducer handles state change logic according to the type of Action and returns a new state. Redux will replace the original state with the new state, thereby updating the state of the entire application.
  5. Notify subscribers: After the state is updated, Redux will notify all listeners registered through the subscribe(listener) method, and let them execute the corresponding callback function, so as to realize the monitoring and response to the state change.
  • How to use Redux DevTools to debug app state and actions

Redux DevTools is a powerful debugging tool that can help us debug the state and operation of Redux applications. It provides some useful functions, including state time travel, operation playback, state snapshot, etc., making it easier for us to debug and monitor the state changes of Redux applications.

Using Redux DevTools is very simple. You only need to introduce the redux-devtools-extension middleware through the applyMiddleware method when creating a Store. For example:

import {
    
     createStore, applyMiddleware } from 'redux';
import {
    
     composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  composeWithDevTools(
    applyMiddleware(/* 中间件 */)
  )
);

// ...

After introducing the redux-devtools-extension middleware, we can see the state changes of the application, as well as the corresponding actions and operations in the Redux DevTools panel in the browser's developer tools. We can use the time travel function to trace back the state changes of the application, and we can also re-execute the previous operation through the replay function.

Redux DevTools also supports exporting and importing state snapshots, which is convenient for sharing the state of the application with team members for collaborative debugging and problem solving.

In short, Redux DevTools is a very powerful and practical debugging tool that can help us better understand and debug the state and operation of Redux applications and improve development efficiency.

Getting started with React-Redux

react+redux

React-Redux is an official library that combines React and Redux. It provides a way to manage global state in React applications, making data transfer and state management between components easier and more maintainable. Here's how to get started with React-Redux:

  1. Introduce the core concepts of React-Redux: In React-Redux, there are two core concepts, namely Providerand connect. Provider is a React component that is used to pass the Redux store to all components in the React application, so that the components can access the global state. connectIt is a higher order function (Higher Order Function) used to connect React components to Redux store, so as to realize data transfer and state management between components and Redux store.

  2. How to connect React components to Redux store: connectReact components can be connected to Redux using functions store. Components can be connected to Redux by calling the function when the component is defined connect, and passing in the required parameters and callback function . storeAfter connecting, the component can modify the global state by propsaccessing storethe state in Redux and storedispatching to Redux.action

  3. How to use React-Redux's higher-order components and hooks to simplify code: React-Redux provides some higher-order components and hooks that can help simplify the interaction code between components and the Redux store. For example, mapStateToPropsand mapDispatchToPropsparameters can help components define how to get state and dispatch from the Redux store action, thereby reducing the tedious code that handles the Redux store in the component. In addition, React-Redux also provides some hooks, such as useSelectorand useDispatch, which can more easily access the state and dispatch of the Redux store in function components action.

By learning the core concepts and usage of React-Redux, developers can manage global state in React applications more flexibly and efficiently, thus building more powerful and maintainable applications. The next part will dive further into the advanced usage and best practices of React-Redux.

Practice: Build a TodoList application with React-Redux

react+redux

In this part, we will use a practical example to demonstrate how to use React-Redux to build a TodoList application, and introduce how to use Redux middleware to handle asynchronous operations and side effects.

  1. Create a basic TodoList application and use Redux to manage state: First, we will create a basic TodoList application, including functions such as adding, removing, and marking completion. Then, we will use Redux to manage the state of the TodoList application, including the list of to-do items, adding new to-do items, and marking to-do items as complete.

  2. Introduce how to use React-Redux to connect React components and Redux store: Next, we will use React-Redux to connect React components and Redux store in the TodoList application. By using the connect function in the component and defining the mapStateToProps and mapDispatchToProps parameters, we can connect the React component with the Redux store, so as to realize the function of accessing the state in the Redux store and dispatching actions.

  3. Introduce how to use Redux middleware to handle asynchronous operations and side effects: In practical applications, we often need to handle asynchronous operations and side effects, such as getting data from the server or executing asynchronous business logic. At this time, Redux middleware can come in handy. We will introduce how to use Redux middleware to handle asynchronous operations and side effects, such as using redux-thunk middleware to handle asynchronous actions, and redux-saga middleware to handle complex side effects and business logic.

Below is a simple sample code showing how to build a TodoList application using React-Redux.

Through this practical example, you will gain a deep understanding of how to use React-Redux to build a complete application, and learn how to use Redux middleware to handle asynchronous operations and side effects, making your application more powerful and flexible.

First, we need to install the necessary dependencies: react、react-dom、redux、react-redux, and optionally redux-thunkfor handling asynchronous operations. It can be installed with the following command:

npm install react react-dom redux react-redux redux-thunk

Next, we can create a Redux store and define the corresponding actionand reducerto handle application state updates.

store.js

import {
    
     createStore } from 'redux';
import todoReducer from './reducers/todoReducer';

// 创建Redux store
const store = createStore(todoReducer);

export default store;

actions.js

// 定义action类型
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const TOGGLE_TODO = 'TOGGLE_TODO';

// 定义action creators
export const addTodo = (text) => ({
    
    
  type: ADD_TODO,
  payload: {
    
    
    id: new Date().getTime(),
    text,
    completed: false,
  },
});

export const deleteTodo = (id) => ({
    
    
  type: DELETE_TODO,
  payload: {
    
     id },
});

export const toggleTodo = (id) => ({
    
    
  type: TOGGLE_TODO,
  payload: {
    
     id },
});

reducers.js

import {
    
     ADD_TODO, DELETE_TODO, TOGGLE_TODO } from '../actions';

// 定义初始状态
const initialState = [];

// 定义reducer函数
const todoReducer = (state = initialState, action) => {
    
    
  switch (action.type) {
    
    
    case ADD_TODO:
      return [...state, action.payload];
    case DELETE_TODO:
      return state.filter(todo => todo.id !== action.payload.id);
    case TOGGLE_TODO:
      return state.map(todo => {
    
    
        if (todo.id === action.payload.id) {
    
    
          return {
    
     ...todo, completed: !todo.completed };
        }
        return todo;
      });
    default:
      return state;
  }
};

export default todoReducer;


Next, we can create React components and use React-Redux to connect the components and the Redux store to get state from the store and trigger state updates.

TodoList.js

import React from 'react';
import {
    
     connect } from 'react-redux';
import {
    
     addTodo, deleteTodo, toggleTodo } from '../actions';

class TodoList extends React.Component {
    
    
  handleAddTodo = () => {
    
    
    const {
    
     dispatch } = this.props;
    const text = prompt('请输入Todo项的内容:');
    if (text) {
    
    
      dispatch(addTodo(text));
    }
  };

  handleDeleteTodo = (id) => {
    
    
    const {
    
     dispatch } = this.props;
    dispatch(deleteTodo(id));
  };

  handleToggleTodo = (id) => {
    
    
    const {
    
     dispatch } = this.props;
    dispatch(toggleTodo(id));
  };

  render() {
    
    
    const {
    
     todos } = this.props;
    return (
      <div>
        <h2>Todo List</h2>
        <ul>
          {
    
    todos.map(todo => (
            <li key={
    
    todo.id}>
              <span
                style={
    
    {
    
     textDecoration: todo.completed ? 'line-through' : 'none' }}
                onClick={
    
    () => this.handleToggleTodo(todo.id)}
              >
                {
    
    todo.text}
              </span>
              <button onClick={
    
    () => this.handleDeleteTodo(todo.id)}>删除</button
       </li>
      ))}
    </ul>
    <button onClick={
    
    this.handleAddTodo}>添加Todo</button>
  </div>
);
}
}

// 定义mapStateToProps函数,用于将Redux store中的状态映射到组件的props
const mapStateToProps = (state) => {
    
    
return {
    
    
todos: state, // 这里将整个state作为todos传递给组件
};
};

// 使用connect函数连接组件和Redux store,并导出连接后的组件
export default connect(mapStateToProps)(TodoList);

Finally, we need to use components in the application's entry file <Provider>to wrap the Redux store in the application so that the entire application can access the Redux store.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {
    
     Provider } from 'react-redux';
import store from './store';
import TodoList from './components/TodoList';

ReactDOM.render(
  <Provider store={
    
    store}>
    <TodoList />
  </Provider>,
  document.getElementById('root')
);

This is just a simple example. In fact, a complete React-Redux application may contain more complex state management and component connection logic, but this example can be used as a starting point to help you understand how to use React-Redux to build a basic TodoList application. Hope to help you!

Advanced features of React-Redux

insert image description here

React-Redux is a powerful state management library. In addition to the basic function of connecting React components and Redux store, it also provides some advanced features to help developers manage complex application states more efficiently.

  1. Using Selectors to access Redux state
    Selectors is a function for getting data from the Redux store, which can help us access some data of the Redux state in React components without having to fetch the entire state tree. Selectors can help us calculate and transform Redux state in components, so that we can use Redux state more flexibly. For example, we can use Selectors to filter, sort, or calculate derived values ​​for some state, thus avoiding heavy calculations or repeated code in components.

Here is an example using Selectors:

// 定义一个Selector,用于从Redux状态树中获取todos数据
const getTodos = (state) => state.todos;

// 在React组件中使用Selector
import {
    
     useSelector } from 'react-redux';

const TodoList = () => {
    
    
  // 使用useSelector Hook获取Redux状态
  const todos = useSelector(getTodos);

  // 在组件中使用todos数据
  // ...
};

  1. Use multiple Redux stores and namespaces to handle complex application state
    In some cases, a single Redux store may not be able to meet the state management needs of complex applications. React-Redux allows us to use multiple Redux stores in the application to better organize and manage the state of the application. We can use different Redux stores to manage different state modules, so as to achieve finer-grained state management and better application architecture.

In addition, React-Redux also supports the use of namespaces to isolate the state of different modules, thereby avoiding state conflicts between different modules. By setting different namespaces when creating a store, the states of different modules can be managed under different namespaces, thereby achieving better state isolation and management.

For example, we can specify multiple reducers in the configuration of the Redux store to manage the state of different modules:

import {
    
     configureStore } from '@reduxjs/toolkit';
import todosReducer from './todosSlice';
import userReducer from './userSlice';

// 创建多个reducer来管理不同模块的状态
const store = configureStore({
    
    
  reducer: {
    
    
    todos: todosReducer,
    user: userReducer,
  },
});

// 在组件中使用不同命名空间的状态
import {
    
     useSelector } from 'react-redux';

const TodoList = () => {
    
    
  const todos = useSelector(state => state.todos); // 使用todos命名空间的状态
  const user = useSelector(state => state.user); // 使用user命名空间的状态

  // 渲染待办事项列表和用户信息
  // ...
};

By using multiple Redux stores and namespaces, we can better organize and isolate the state of different modules, making the application state clearer and easier to maintain.

  1. Use Redux Toolkit to simplify Redux code
    Redux Toolkit is an officially recommended tool set for Redux. It provides a series of tools and conventions that can help us simplify the development process of Redux, reduce boilerplate code, and improve development efficiency.

Redux Toolkit provides a modern way to create a Redux store and integrates commonly used Redux middleware, such as Redux Thunk and Redux Saga, to handle asynchronous operations. At the same time, Redux Toolkit also provides a simplified state update method called "Slice", which can help us define and process Redux state more intuitively.

Here is an example using Redux Toolkit:

import {
    
     createSlice, configureStore } from '@reduxjs/toolkit';

// 定义一个Redux Slice
const todosSlice = createSlice({
    
    
  name: 'todos',
  initialState: [],
  reducers: {
    
    
    addTodo: (state, action) => {
    
    
      //
  // 处理添加Todo的逻辑
},
deleteTodo: (state, action) => {
    
    
  // 处理删除Todo的逻辑
},
toggleTodo: (state, action) => {
    
    
  // 处理切换Todo状态的逻辑
},
},
});

// 获取Redux状态和Actions
export const {
    
     addTodo, deleteTodo, toggleTodo } = todosSlice.actions;

// 创建Redux store
const store = configureStore({
    
    
reducer: todosSlice.reducer,
});

// 在React组件中使用Redux Toolkit
import {
    
     useSelector, useDispatch } from 'react-redux';
import {
    
     addTodo, deleteTodo, toggleTodo } from './todosSlice';

const TodoList = () => {
    
    
const todos = useSelector(state => state); // 使用Selector获取Redux状态
const dispatch = useDispatch(); // 使用useDispatch Hook获取dispatch函数

// 在组件中使用Redux Toolkit的Actions
const handleAddTodo = (todo) => {
    
    
dispatch(addTodo(todo)); // dispatch addTodo Action
};

const handleDeleteTodo = (id) => {
    
    
dispatch(deleteTodo(id)); // dispatch deleteTodo Action
};

const handleToggleTodo = (id) => {
    
    
dispatch(toggleTodo(id)); // dispatch toggleTodo Action
};

// 在组件中使用todos数据和Redux Toolkit的Actions
// ...
};


By using advanced features such as Selectors, multiple Redux stores and namespaces, and Redux Toolkit, we can manage and organize complex application states more flexibly, and improve code maintainability and development efficiency.

Redux Toolkit also provides some middleware for handling asynchronous operations and side effects, such as createAsyncThunkand createEntityAdapter. These tools help us handle asynchronous requests, handle errors, and update Redux state more easily.

By using Redux Toolkit, we can simplify Redux code, reduce boilerplate code, improve development efficiency, and make Redux code more readable and easy to maintain.

The above are some advanced features of React-Redux, which can help us better manage and organize complex application states, and simplify the writing of Redux code. In actual projects, according to application requirements, you can choose to use these advanced features to improve development efficiency and code quality.

in conclusion

react+redux

React-Redux is a powerful state management tool that provides a reliable way for React applications to manage application state. Through the core concepts of Redux, including Action, Reducer, and Store, we can centrally manage the state of the application and realize a single data source and immutability of the state, thereby improving the maintainability and testability of the application.

In React-Redux, we use the Provider component to inject the Redux store into the React application, and then use the connect high-level component or hooks to connect the React component and the Redux store to achieve state transfer and update. Through the workflow of Redux, we can clearly understand how Action triggers Reducer to modify the application state, and how to use Redux DevTools to debug application state and operation.

In addition, React-Redux also provides some advanced features, such as Selectors, multiple Redux stores and namespaces, Redux Toolkit, etc., which can help us better manage complex application states and simplify Redux code writing.

In the summary, we emphasized the importance and role of React-Redux in modern React applications, summarized the core concepts and usage methods of Redux and React-Redux, and encouraged readers to try to use React-Redux in their own React projects. Manage application status to improve application development efficiency and code quality.

Complete sample code of TodoList

react+redux

// store.js

import {
    
     createStore } from "redux";
import rootReducer from "./reducers";

const store = createStore(rootReducer);

export default store;

// reducers.js

import {
    
     ADD_TODO, TOGGLE_TODO, DELETE_TODO } from "./actionTypes";

const initialState = {
    
    
  todos: []
};

const rootReducer = (state = initialState, action) => {
    
    
  switch (action.type) {
    
    
    case ADD_TODO:
      return {
    
    
        ...state,
        todos: [...state.todos, action.payload]
      };
    case TOGGLE_TODO:
      return {
    
    
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload ? {
    
     ...todo, completed: !todo.completed } : todo
        )
      };
    case DELETE_TODO:
      return {
    
    
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload)
      };
    default:
      return state;
  }
};

export default rootReducer;

// actions.js

import {
    
     ADD_TODO, TOGGLE_TODO, DELETE_TODO } from "./actionTypes";

let nextTodoId = 0;

export const addTodo = text => ({
    
    
  type: ADD_TODO,
  payload: {
    
    
    id: nextTodoId++,
    text,
    completed: false
  }
});

export const toggleTodo = id => ({
    
    
  type: TOGGLE_TODO,
  payload: id
});

export const deleteTodo = id => ({
    
    
  type: DELETE_TODO,
  payload: id
});

// actionTypes.js

export const ADD_TODO = "ADD_TODO";
export const TOGGLE_TODO = "TOGGLE_TODO";
export const DELETE_TODO = "DELETE_TODO";

// TodoList.js

import React from "react";
import {
    
     connect } from "react-redux";
import {
    
     addTodo, toggleTodo, deleteTodo } from "./actions";

const TodoList = ({
     
      todos, addTodo, toggleTodo, deleteTodo }) => {
    
    
  // ... TodoList组件的实现
};

const mapStateToProps = state => {
    
    
  return {
    
    
    todos: state.todos
  };
};

const mapDispatchToProps = dispatch => {
    
    
  return {
    
    
    addTodo: text => dispatch(addTodo(text)),
    toggleTodo: id => dispatch(toggleTodo(id)),
    deleteTodo: id => dispatch(deleteTodo(id))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

In the above example, we used the connect function of React-Redux to connect the TodoList component and the Redux store. Through the mapStateToProps function, we map the todos state in the Redux store to the props of the TodoList component, so that the todos data can be accessed in the component. Through the mapDispatchToProps function, we map the three Action Creators addTodo, toggleTodo and deleteTodo to the props of the TodoList component, so that these Actions can be triggered in the component to update the application state.

reference resources

react+redux

Here are some official documentation and other great resources for your reference to learn React-Redux in depth:

  1. React-Redux official documentation: https://react-redux.js.org/
    The official documentation is the best resource for learning React-Redux. It provides detailed introductions, tutorials, and sample code, covering the core concepts, usage, and advanced features of React-Redux.

  2. Redux official document: https://redux.js.org/
    Redux is the underlying state management library of React-Redux. Understanding the basic concepts and usage of Redux is very helpful for learning React-Redux. The official Redux documentation provides detailed introductions, tutorials, and sample code.

  3. Redux Chinese documentation: https://redux.js.org.cn/
    Redux’s Chinese documentation provides detailed introductions, tutorials and sample codes for Redux, which is more friendly to Chinese users.

  4. Redux Toolkit official documentation: https://redux-toolkit.js.org/
    Redux Toolkit is an officially recommended toolkit for simplifying Redux code. It integrates common functions of Redux and provides some tools and utility functions to simplify Redux development . The official Redux Toolkit documentation provides a detailed introduction and sample code.

  5. React-Redux GitHub repository: https://github.com/reduxjs/react-redux
    React-Redux's GitHub repository contains the source code, examples and documentation of React-Redux. You can check out the latest updates and commits here for the latest developments and improvements in React-Redux.

  6. Redux official example application: https://redux.js.org/introduction/examples
    Redux officially provides a series of example applications, covering applications of different complexity and purposes, including Todo List, Reddit, etc. These sample applications provide actual code and implementation to help you better understand and apply Redux and React-Redux.

  7. React-Redux community resources: https://react-redux.js.org/community
    React-Redux official documentation provides a wealth of community resources, including FAQs, common errors, tutorials, blog posts and videos, etc. These resources can Help you learn React-Redux in depth and gain more experience and knowledge from the community.

Hope these resources help you learn more about React-Redux! I wish you success in using React-Redux to manage React application state.

Guess you like

Origin blog.csdn.net/u011897062/article/details/130323825