Redux 是一个用于管理 JavaScript 应用程序状态的库。它通过中央存储来提供一致的状态管理,使得大型应用程序的状态管理更加容易。

Redux 的核心概念

  • State: 状态是应用程序当前状态的表示。在 Redux 中,状态是单一来源的,这意味着整个应用的状态都被存储在一个单一的 store 对象中。

  • Action: Action 是一个描述事件的对象,用于触发状态变更。Action 是无副作用的,并且是同步的。

  • Reducer: Reducer 是一个函数,它接收当前的 state 和一个 action,然后返回一个新的 state。Reducer 是纯函数,它不改变传入的参数。

  • Store: Store 是 Redux 的核心,它负责管理状态,并提供获取状态和 dispatch action 的方法。

如何使用 Redux

  1. 安装 Redux 库:

    npm install redux
    
  2. 创建 Store:

    import { createStore } from 'redux';
    
    const store = createStore(reducer);
    
  3. 定义 Reducer:

    function reducer(state = {}, action) {
        switch (action.type) {
            case 'ACTION_TYPE':
                return { ...state, ...action.payload };
            default:
                return state;
        }
    }
    
  4. 在组件中使用 Redux:

    import React from 'react';
    import { connect } from 'react-redux';
    
    const MyComponent = ({ myProp }) => {
        return <div>{myProp}</div>;
    };
    
    const mapStateToProps = state => ({
        myProp: state.myProp
    });
    
    export default connect(mapStateToProps)(MyComponent);
    

扩展阅读

想要更深入地了解 Redux,可以阅读以下文章:

希望这些信息能帮助您更好地理解 Redux!🚀