UseReducer complex state management in react

一、useReduce

The reducer official website tutorial
useReducer is a Hook provided by React for state management. It can replace useState and is more suitable for processing complex state logic.

useReducer Accepts a reducerfunction and a function 初始状态that returns the current state and a dispatchfunction to trigger a state update. The reducer function accepts two parameters, the current state and an action object, and returns a new state.

The main benefit of using useReduceris that the state update logic can be concentrated in one place, making the component's logic clearer and maintainable. In comparison useState, useReducerit is more suitable for states with multiple sub-values ​​or complex logical dependencies.
Insert image description here

Here is a simple example of how to use useReducer:

import React, {
    
     useReducer } from 'react';

const initialState = 0; // 初始状态

function reducer(state, action) {
    
     // reducer 函数
  switch (action.type) {
    
    
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return initialState;
    default:
      throw new Error();
  }
}

function Counter() {
    
    
  const [count, dispatch] = useReducer(reducer, initialState); // 使用 useReducer
  return (
    <div>
      Count: {
    
    count}
      <button onClick={
    
    () => dispatch({
    
     type: 'increment' })}>
        Increment
      </button>
      <button onClick={
    
    () => dispatch({
    
     type: 'decrement' })}>
        Decrement
      </button>
      <button onClick={
    
    () => dispatch({
    
     type: 'reset' })}>
        Reset
      </button>
    </div>
  );
}

In the above example, the reducer function receives a state and an action object, and returns a new state based on different action types. Through useReducer, the Counter component can update the status based on different button clicks and render the latest status to the page.

Using useReducer can better organize and manage complex state logic, while also improving the readability and maintainability of the code.

二、redux、react-redux

In React projects, you can use React-Redux to achieve data sharing. React-Redux is a library for using Redux with React, which provides a Provider component for providing a Redux store to components throughout the application.

Here is an example of data sharing using React-Redux:

  1. Install React-Redux:

    npm install react-redux
    
  2. Create a Redux store:

    import {
          
           createStore } from "redux";
    
    // 定义初始状态和reducer
    const initialState = {
          
          
      data: null,
    };
    
    const reducer = (state = initialState, action) => {
          
          
      switch (action.type) {
          
          
        case "SET_DATA":
          return {
          
          
            ...state,
            data: action.payload,
          };
        default:
          return state;
      }
    };
    
    // 创建store
    const store = createStore(reducer);
    
  3. Use the Provider component in the root component to provide the Redux store:

    import {
          
           Provider } from "react-redux";
    import store from "./store";
    
    const App = () => {
          
          
      return (
        <Provider store={
          
          store}>
          {
          
          /* 其他组件 */}
        </Provider>
      );
    };
    
    export default App;
    
  4. Use the connect function in components that need to share data to connect to the Redux store:

    import {
          
           connect } from "react-redux";
    
    const DataComponent = (props) => {
          
          
      return (
        <div>
          <p>共享的数据: {
          
          props.data}</p>
          <button onClick={
          
          () => props.setData("Hello, React-Redux!")}>
            设置数据
          </button>
        </div>
      );
    };
    
    const mapStateToProps = (state) => ({
          
          
      data: state.data,
    });
    
    const mapDispatchToProps = (dispatch) => ({
          
          
      setData: (data) => dispatch({
          
           type: "SET_DATA", payload: data }),
    });
    
    export default connect(mapStateToProps, mapDispatchToProps)(DataComponent);
    
  5. Now DataComponentthe component can access Redux storethe shared data and dispatch actionto update the data.

connectIn the above example, a function is used to DataComponentconnect the component to Redux store. connectThe function accepts two parameters: mapStateToPropsand mapDispatchToProps. mapStateToPropsThe function is used to Redux storemap the state in the component to the component props, and mapDispatchToPropsthe function will action creatorsbe mapped to the component propsso that the component can dispatch actionupdate data.

Note: When using , make sure to use component providers React-Reduxin the root component so that components throughout the application can access the shared data.ProviderRedux store

Guess you like

Origin blog.csdn.net/jieyucx/article/details/134142526