美文网首页
redux 简单实现数据管理

redux 简单实现数据管理

作者: 暴躁程序员 | 来源:发表于2023-09-06 17:24 被阅读0次

    一、redux 特点

    1. redux 是集中管理共享状态的 JS 插件库
    2. store 用于存储状态的容器,唯一状态树,即:store 的 state 是一个对象,且是唯一的
    3. reducer 纯函数,只读不修改 store 的历史 state
    4. action 组件改变 store 状态时,发布的动作
    5. reducer 纯函数,在不改变 store 状态的情况下返回最新 state 状态
    

    二、redux 管理数据(单个 reducer)

    1. redux 主要方法

    createStore(reducer)          创建 store
    store.getState()              获取 state
    store.dispatch(action)        发布 action
    store.subscribe(method)       订阅 method
    

    2. redux 数据管理分析

    1. 如何创建 store
    将 reducer 函数作为参数传入 createStore(reducer) 方法中
    
    1. 如何在组件中获取 store 中的数据
    在组件中通过 store.getState() 方法获取 store 中数据
    
    1. 如何修改 store 中数据
    1. 首先,在组件中通过 store.dispatch(action) 方法派发 action,告诉 store 需要修改哪个reducer,怎么修改
    2. 然后,在 reducer.js 中,结合原store数据和action,返回新的 store 数据
    3. 最后,在组件中通过 store.subscribe(method) 方法感应store数据变化并触发 method 回调,并在 method 回调中修改组件状态数据
    

    3. redux 示例

    1. 安装 redux
    npm install redux -S
    
    1. 创建 store,新建 src\store\index.js
      将 reducer 函数作为参数传入 createStore() 中用于创建 store
    import { createStore } from "redux";
    import reducer from "./reducer";
    
    // 传入 reducer 创建store
    const store = createStore(
      reducer
    );
    export default store;
    
    1. 创建 reducer,新建 src\store\reducer.js
      reducer 是自定义的函数,接收当前 state 和 action 两个参数,返回最新 state
    const defaultState = {
      inputValue: "alias",
    };
    
    // 2. 在组件中执行 store.dispatch(action) 后触发此函数,在此函数中可获取到历史数据 defaultState 和 在组件中 dispatch 的 action
    // 然后在不更改历史数据 defaultState 的前提下,通过 action 获取到更新后的数据
    // 然后在历史数据 defaultState 的基础上构建新的 store 数据 newState,并返回 newState
    const reducer = (state = defaultState, action) => {
      switch (action.type) {
        case "CHANGE_INPUT_VALUE":
          const newState = Object.assign({}, defaultState, {
            inputValue: action.payload,
          });
          return newState;
        default:
          return state;
      }
    };
    
    export default reducer;
    
    1. 在组件中使用 store,创建action,新建 src\pages\test\index.js
      action 是自定义的对象,用于发布变更的信息
    import React, { Component } from "react";
    import store from "../store";
    class Test extends Component {
      constructor(props) {
        super(props);
        this.state = {
          store: store.getState(),
        };
        this.fnChangeInput = this.fnChangeInput.bind(this);
        this.listenChangeInput = this.listenChangeInput.bind(this);
    
        // 3. 在 src\store\reducer.js 中的 reducer 函数返回新 store 后触发组件中 store.subscribe() 的回调更改组件中数据
        store.subscribe(this.listenChangeInput);
      }
      render() {
        return (
          <>
            <h1> redux 公共数据管理 </h1>
            <div>
              <div>
                <label htmlFor="uname">用户名:</label>
                <input
                  style={{ width: "200px", margin: "10px" }}
                  placeholder="请输入用户名"
                  defaultValue={this.state.store.inputValue}
                  onChange={this.fnChangeInput}
                />
              </div>
              <div>{this.state.store.inputValue}</div>
            </div>
          </>
        );
      }
    
      fnChangeInput(e) {
        const action = {
          type: "CHANGE_INPUT_VALUE",
          payload: e.target.value,
        };
    
        // 1. 组件通过 dispatch 方法派发action告诉 store 需要修改哪个reducer,怎么修改,此方法执行后会触发 src\store\reducer.js 中的 reducer 函数
        store.dispatch(action);
      }
      listenChangeInput() {
        this.setState({ store: store.getState() });
      }
    }
    export default Test;
    

    三、redux 数据管理(多个 reducer)

    1. redux 主要方法

    createStore(reducer)          创建 store
    combineReducers({})           合并 reducer
    store.getState()              获取 state
    store.dispatch(action)        发布 action
    store.subscribe(method)       订阅 method
    

    2. redux 数据管理分析

    1. 如何创建 store
    将 reducer 函数作为参数传入 createStore(reducer) 方法中
    
    1. 如何在组件中获取 store 中的数据
    在组件中通过 store.getState().模块名 获取 store 中数据
    
    1. 如何合并多个reducer
    在 reducer.js 中将多个 reduer 作为参数传入 combineReducers({reduer1,reduer2}) 方法,合并成新的 reducer
    
    1. 如何修改 store 中数据
    1. 首先,在组件中通过 store.dispatch(action) 方法派发 action,告诉 store 需要修改哪个reducer,怎么修改
    2. 然后,在 reducer.js 中,结合原store数据和action,返回新的 store 数据
    3. 最后,在组件中通过 store.subscribe(method) 方法感应store数据变化并触发 method 回调,并在 method 回调中修改组件状态数据
    

    3. redux 示例

    1. 安装 redux
    npm install redux -S
    
    1. 创建 store,新建 src\store\index.js
      将合并后的 reducer 函数作为参数传入 createStore() 中用于创建 store
    import { createStore } from 'redux';
    import reducer from './reducer';
    
    // 传入 reducer 创建store
    const store = createStore(reducer);
    export default store;
    
    1. 创建 reducer,新建 src\store\reducer.js
      reducer 是自定义的函数,接收当前 state 和 action 两个参数,返回最新 state
      通过 combineReducers() 方法合并多个 reducer
    import { combineReducers } from "redux";
    
    // 输入框模块
    const defaultState = {
      inputValue: "alias",
    };
    const inputValueReducer = (state = defaultState, action) => {
      switch (action.type) {
        case "CHANGE_INPUT_VALUE":
          const newState = Object.assign({}, state, {
            inputValue: action.payload,
          });
          return newState;
        default:
          return state;
      }
    };
    
    // 数字迭代模块
    const initialNum = {
      num: 0,
    };
    const addNumReducer = (state = initialNum, action) => {
      switch (action.type) {
        case "ADD_NUM":
          const newState = Object.assign({}, state, {
            num: state.num + action.payload,
          });
          return newState;
        default:
          return state;
      }
    };
    
    const rootReducer = combineReducers({
      inputValueReducer,
      addNumReducer,
    });
    export default rootReducer;
    
    1. 在组件中使用 store,新建 src\pages\test\index.js
      action 是自定义的对象,用于发布变更的信息
    import React, { Component } from "react";
    import store from "../store";
    class Test extends Component {
      constructor(props) {
        super(props);
        this.state = {
          ...store.getState()
        };
        this.fnChangeInput = this.fnChangeInput.bind(this);
        this.listenChangeInput = this.listenChangeInput.bind(this);
        this.fnAddNum = this.fnAddNum.bind(this);
        this.listenAddNum = this.listenAddNum.bind(this);
    
        store.subscribe(this.listenChangeInput);
        store.subscribe(this.listenAddNum);
      }
      render() {
        return (
          <>
            <h1>redux 公共数据管理</h1>
            <div>
              <div>
                <label htmlFor="uname">用户名:</label>
                <input
                  style={{ width: "200px", margin: "10px" }}
                  placeholder="请输入用户名"
                  defaultValue={this.state.inputValueReducer.inputValue}
                  onChange={this.fnChangeInput}
                />
              </div>
              <div>{this.state.inputValueReducer.inputValue}</div>
            </div>
            <div>
              <button onClick={this.fnAddNum} >num ++</button>
              <div>{this.state.addNumReducer.num}</div>
            </div>
          </>
        );
      }
    
      fnChangeInput(e) {
        const action = {
          type: "CHANGE_INPUT_VALUE",
          payload: e.target.value,
        };
    
        store.dispatch(action);
      }
      listenChangeInput() {
        this.setState(()=>{
          return { ...store.getState() }
        });
      }
      fnAddNum(){
        const action = {
          type: "ADD_NUM",
          payload: 1,
        };
    
        store.dispatch(action);
      }
      listenAddNum(){
        this.setState(()=>{
          return { ...store.getState() }
        });
        console.log(store.getState());
      }
    }
    export default Test;
    

    相关文章

      网友评论

          本文标题:redux 简单实现数据管理

          本文链接:https://www.haomeiwen.com/subject/qnokvdtx.html