Redux 基本概念

  1. Redux 是一个流行的状态管理库,使用单一状态树来管理整个应用的状态;
  2. 前面存储变量的对象,给他一个确切的定义——状态仓库 (store),不同于对象操作的是:任何时候你都不能直接去更改状态仓库 (store) 中的值,而是需要使用纯函数进行状态修改;

什么是纯函数?​如果函数的调用参数相同,则永远返回相同的结果;它不依赖于程序执行期间函数外部任何状态或数据的变化,必须只依赖于其输入参数;该函数不会产生任何可观察的副作用;

Redux 原理​

  1. Redux 的核心概念包括:​

    1. 单一数据源:整个应用的状态存储在一个对象树中,这个对象树仅存在于一个 store 中;
    2. 状态是只读的:唯一改变状态的方法是触发 actionaction 是一个描述发生什么的对象;​
    3. 使用纯函数来执行修改:为了描述 action 如何改变状态树,需要编写 reducers
  2. Reduxstore 是由 createStore 创建的,它包含以下几个方法:​

    1. getState:获取当前状态;
    2. dispatch:触发 action
    3. subscribe:添加监听器;​
    4. replaceReducer:替换当前 reducer;​

Redux 基本使用

示例代码

  1. 安装 Redux 和 React-Redux

    npm install redux react-redux
    
  2. 创建 Action

    // actions.js​
    export const increment = () => ({ type: 'INCREMENT' });​
    export const decrement = () => ({ type: 'DECREMENT' });
    
  3. 创建 Reducer

    // reducer.js​
    const initialState = { count: 0 };​
    ​
    const counterReducer = (state = initialState, action) => {​
      switch (action.type) {​
        case 'INCREMENT':​
          return { ...state, count: state.count + 1 };​
        case 'DECREMENT':​
          return { ...state, count: state.count - 1 };​
        default:​
          return state;​
      }​
    };​
    ​
    export default counterReducer;
    
  4. 创建 Store

    // store.js​
    import { createStore } from 'redux';​
    import counterReducer from './reducer';​
    ​
    const store = createStore(counterReducer);​
    ​
    export default store;
    
  5. 使用 Provider 提供 Store

    // index.js​
    import React from 'react';​
    import ReactDOM from 'react-dom';​
    import { Provider } from 'react-redux';​
    import store from './store';​
    import App from './App';​
    ​
    ReactDOM.render(​
      <Provider store={store}>​
        <App />​
      </Provider>,​
      document.getElementById('root')​
    );
    
  6. 连接组件

    // Counter.js​
    import React from 'react';​
    import { useSelector, useDispatch } from 'react-redux';​
    import { increment, decrement } from './actions';​
    ​
    const Counter = () => {​
      const count = useSelector((state) => state.count);​ // 从 store 中提取特定数据的函数
      const dispatch = useDispatch();​ // 发送 action 的方法
    ​
      return (​
        <div>​
          <h1>{count}</h1>​
          <button onClick={() => dispatch(increment())}>Increment</button>​
          <button onClick={() => dispatch(decrement())}>Decrement</button>​
        </div>​
      );​
    };​
    ​
    export default Counter;
    

Redux 流程图

  1. 全局通常只有一个 Store 存储 State

  2. Component 中在某些情况会派发 Action (这些 Action 是提前定义好的)

  3. Reducer 会接收到这些 Action,并且在 Reducer 中会返回一个新的 State,作为 StoreState

  4. State 发生更新之后会触发通知,告知订阅者数据发生了改变;

  5. 订阅者拿到最新的数据 (在 props 中),更新到 jsx 中,界面发生改变;

打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

你好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. Redux 基本概念
  2. 2. Redux 原理​
  3. 3. Redux 基本使用
    1. 3.1. 示例代码
    2. 3.2. Redux 流程图