【Redux】redux的使用详解

4 篇文章 0 订阅
1 篇文章 0 订阅

Redux的使用详解

Redux的核心思想

理解纯函数

1. 为什么要使用redux

  • JavaScript开发的应用程序,已经变得越来越复杂了:

    • JavaScript需要 管理的状态越来越多,越来越复杂
    • 这些状态包括:服务器返回的数据、缓存数据、用户操作产生的文件数据等等,也包括一些 UI的状态,比如 某些元素是否被选中,是否显示加载动效,当前分页
  • 管理不断变化的state是非常困难的:

  • 状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化;

  • 口 当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪;

  • React是在视图层帮助我们解决了DOM的渲染过程,但是State依然是留给我们自己来管理:

  • 口 无论是组件定义自己的state,还是组件之间的通信通过props进行传递;也包括通过Context进行数据之间的共享

  • 口 React主要负责帮助我们管理视图state如何维护最终还是我们自己来决定

    UI = render(state)

  • Redux就是一个帮助我们管理State的容器:Redux是 JavaScript的状态容器,提供了可预测的状态管理

  • Redux除了和React一起使用之外,它也可以和其他界面库一起使用(比如Vue),并且它非常小(包括依赖在内,只有2kb)

2. Redux的核心理念 - Store

  • Redux的核心理念非常简单。

  • 比如我们有一个朋友列表需要管理:

  • 口 如果我们没有定义统一的规范来操作这段数据,那么整个数据的变化就是无法跟踪的;

  • 口 比如页面的某处通过products.push的方式增加了一条数据;

  • 口 比如另一个页面通过products[0].age = 25修改了一条数据;

    const initialState  = {
      friends:[
        { name: "why",age:18 },
        { name: "kobe", age: 40 },
        { name: 'lilei', age: 30 },
      ]
    }
    
  • 整个应用程序错综复杂,当出现bug时,很难跟踪到底哪里发生的变化;

3. Redux的核心理念 - action

  • Redux要求我们通过action来更新数据:
    • 口 所有数据的变化,必须通过派发 (dispatch) action来更新
    • action是一个普通的JavaScript对象,用来描述这次更新的type和content;
  • 比如下面就是几个更新friends的action:
  • 口 强制使用action的好处是可以清晰的知道数据到底发生了什么样的变化,所有的数据变化都是可跟追、可预测的;
  • 口 当然,目前我们的action是固定的对象
  • 口 真实应用中,我们会通过函数来定义,返回一个action;
const actionl = { type: "ADD_FRIEND", info:{ name: "lucy",age: 20} } 
const action2 = { type: "INC_AGE", index: 0 }
const action3 = { type: "CHANGE_NAME", playload: {index: O newName: "coderwhy"}  } 

4.Redux的核心理念 - reducer

  • 但是如何将state和action联系在一起呢?答案就是reducer

    • 口 reducer是一个纯函数
    • 口 reducer做的事情就是将传入的state和action结合起来生成一个新的state
    function reducer(state = initState,action){
     switch (action.type){
        case "ADD_FRIEND":
          return { ...state,friends:[...state.friends,action.info] }
        case "INC_AGE":
          return {
             ...state,friends:state.friends.map((item,index)=>{
               if(index === action.index){
                 return { ...item,age:item.age+1 }
               }
               return item
             })
          }
        case "CHANGE_NAME":
            return {
               ...state,friends:state.friends.map((item,index)=>{
                 if(index === action.index){
                   return { ...item,name:action.newName}
                 }
                 return item
               })
            }
        default:
          return state
      }
    }
    

Redux的基本使用

Redux的使用过程

    1. 创建一个对象,作为我们要保持的状态;
    1. 创建Store来存储这个state
    • 创建store时,必须创建reducer
    • 我们可以通过 store.getState() 来获取当前的state;
  • 3.通过action来修改state

    • 通过dispatch来派发action;
    • 通常action中都会有type属性,也可以携带其他的数据;
    1. 修改reducer中的处理代码
    • 这里一定要记住,reducer是一个纯函数,不需要直接修改state;
    1. 可以在派发action之前,监听store的变化。

Redux结构划分

  • 如果我们将所有的逻辑代码写到一起,那么当redux变得复杂时代码就难以维护。
    • 口 接下来,我会对代码进行拆分,将store、reducer、action、constants折分成一个个文件。
    • 口 创建 store/index.js文件;
    • 口 创建store/reducer.js文件;
    • 口 创建store/actionCreators.js文件;
    • 口 创建store/constants.js文件;
  • 注意:node中对ES6模块化的支持
    • 口 目前我使用的node版本是v12.16.1, 从node v13.2.0开始,node才对ES6模块化提供了支持:

    • 口 node v13.2.0之前,需要进行如下操作:

      • 在package.json中添加属性:
        • “type”:“module”;
        • 在执行命令中添加口下选项:node --experimental-modules src/index.js;
    • 口 node v13.2.0之后,只需要进行如下操作:

      • 在packagejson中添加属性:“type”:“module”;
  • 注意:导入文件时,需要跟上js后级名;

Redux的使用流程:

// store/index.js
const { createStore } = require('redux');
const reducer = require('./reducer');
//创建的store
const store = createStore(reducer);
module.exports = store;
// store/reducer.js
// 常量
const { CHANGE_NAME, CHANGE_AGE } = require('../store/constance');

// 初始化数据 :创建一个对象,作为我们要保持的状态
const initialState = {
  name: 'why',
  age: 18,
};

// 定义reducer函数:纯函数
// 两个参数:
//  参数一:store当中的目前保存的state
//  参数二:本次需要更新的action(dispatch传入的action)

// 返回值: 它的返回值会作为store之后存储的state
function reducer(state = initialState, action) {
  //   console.log('reducer : ', state, action);
  // 有新数据进行更新的时候,返回新的state
  // 没有新数据更新的时候,那么返回之前的state
  switch (action.type) {
    case CHANGE_NAME:
      return { ...state, name: action.name };
    case CHANGE_AGE:
      return { ...state, age: action.age };
    default:
      return state;
  }
}
module.exports = reducer;
// store/constance.js 需要使用到的常量
//actionCreators 和 reducer 函数中使用字符串常量是一致的,所以将常量抽取到一个独立的contance.js
const CHANGE_NAME = 'CHANGE_NAME';
const CHANGE_AGE = 'CHANGE_AGE';

module.exports = {
  CHANGE_NAME,
  CHANGE_AGE,
};
// store/actionCreators.js 
// 需要派发的action生成过程
const { CHANGE_NAME, CHANGE_AGE } = require('../store/constance');
const changeNameAction = (name) => ({
  type: CHANGE_NAME,
  name,
});

const changeAgeAction = (age) => ({
  type: CHANGE_AGE,
  age,
});

module.exports = { changeNameAction, changeAgeAction };
// 使用redux

/**
 * redux代码优化:
 *  1. 将派发的action生成过程放到一个actionCreators函数中
 *  2. 将定义的所有actionCreators的函数,放到一个独立的文件中: actionCreators.js
 *  3. actionCreators 和 reducer 函数中使用字符串常量是一致的,所以将常量抽取到一个独立的contance.js
 *  4. 将 reducer 和默认值(initialState)放到一个独立的reducer.js文件中,而不是在index.js
 */

const store = require('./store');
// action函数
const { changeNameAction, changeAgeAction } = require('./store/actionCreators');

//通过订阅 得到数据变化
const unsubscribe = store.subscribe(() => {
  console.log('订阅数据的变化', store.getState());
});

//actionCreators:帮助我们创建action

// 修改store当中的数据 : 必须通过 action
// 通过dispatch派发action
store.dispatch(changeNameAction('李雷'));
store.dispatch(changeNameAction('赵虎'));
store.dispatch(changeNameAction('王树'));

// 取消订阅
unsubscribe();

// 修改 age
store.dispatch(changeAgeAction(20));
store.dispatch(changeAgeAction(50));

在这里插入图片描述

react-redux使用

  • 开始之前需要强调一下,redux和react没有直接的关系,你完全可以在React, Angular, Ember, jQuery, or vanilla JavaScript中使用Redux;
  • 尽管这样说,redux依然是和React库结合的更好,因为他们是通过state函数来描述界面的状态,Redux可以发射状态的更新, 让他们作出相应。
  • 虽然我们之前己经实现了connect、Provider这些帮助我们完成连接redux、react的辅助工具,但是实际上redux官方帮助我们提供了 react-redux 的库,可以直接在项目中使用,并且实现的逻辑会更加的严递和高效,
  • 安装react-redux: yarn add react-redux

React结合Redux

redux融入react代码

  • 目前redux在react中使用最多的,所以我们需要将之前编写的redux代码,融入到react中去。
  • 这里创建两个组件
    • Home组件:其中会展示当前的counter值,并且有一个 +1 和 +5 的按钮;
    • Profile组件:其中会展示当前的counter值,并且有一个 -1 和 -5 的按钮;
  • 核心代码主要有两个:
    • 在componentDidMount中定义数据的变化,当数据发生变化的时,重新设置counter;
    • 在发生点击事件时,调用store的dispatch来派发对应的action;
// src/store/index.js
import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);
export default store;
// src/store/reducer.js
import { ADD_NUMBER, SUB_NUMBER } from './constants';
// 初始值
const initialState = {
  counter: 10,
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD_NUMBER:
      return { ...state, counter: state.counter + action.num };
    case SUB_NUMBER:
      return { ...state, counter: state.counter - action.num };
    default:
      return state;
  }
}

export default reducer;
// src/store/constants.js
export const ADD_NUMBER = 'add_number';
export const SUB_NUMBER = 'sub_number';
// src/store/actionCreators.js
import { ADD_NUMBER, SUB_NUMBER } from './constants';
export const addNumberAction = (num) => ({
  type: ADD_NUMBER,
  num,
});
export const subNumberAction = (num) => ({
  type: SUB_NUMBER,
  num,
});
// src/App.jsx
import React, { PureComponent } from 'react';
import Home from './pages/Home.jsx';
import Profile from './pages/Profile.jsx';

import './style.css';

//redux store
import store from './store';

export class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      counter: store.getState().counter,
    };
  }
  componentDidMount() {
    // 在挂载时订阅redux中的state 里 counter 的变化
    store.subscribe(() => {
      const state = store.getState();
      this.setState({ counter: state.counter });
    });
  }

  render() {
    const { counter } = this.state;
    return (
      <div>
        <h1>Redux</h1>
        <h2>App: counter : {counter}</h2>
        <div className="content">
          <Home></Home>
          <Profile></Profile>
        </div>
      </div>
    );
  }
}

export default App;
// src/pages/Home.jsx
import React, { PureComponent } from 'react';

// redux 
import store from '../store';
// action函数
import { addNumberAction } from '../store/actionCreators';

export class Home extends PureComponent {
  constructor() {
    super();
    this.state = {
      counter: store.getState().counter,
    };
  }
  componentDidMount() {
    // 在挂载时订阅redux中的state 里 counter 的变化
    store.subscribe(() => {
      const state = store.getState();
      this.setState({ counter: state.counter });
    });
  }
  addNumber(num) {
    // 点击事件:通过dispatch 发送  action :addNumberAction
    store.dispatch(addNumberAction(num));
  }
  render() {
    const { counter } = this.state;
    return (
      <div className="home">
        <h2>Home: counter : {counter}</h2>
        <button onClick={(e) => this.addNumber(1)}>+1</button>
        <button onClick={(e) => this.addNumber(5)}>+5</button>
        <button onClick={(e) => this.addNumber(8)}>+8</button>
      </div>
    );
  }
}

export default Home;
import React, { PureComponent } from 'react';
import store from '../store';
import { subNumberAction } from '../store/actionCreators';
export class Profile extends PureComponent {
  constructor() {
    super();
    this.state = {
      counter: store.getState().counter,
    };
  }
  componentDidMount() {
    store.subscribe(() => {
      const state = store.getState();
      this.setState({ counter: state.counter });
    });
  }
  subNumber(num) {
    store.dispatch(subNumberAction(num));
  }
  render() {
    const { counter } = this.state;
    return (
      <div className="profile">
        <h2>Profile: counter : {counter}</h2>
        <button onClick={(e) => this.subNumber(1)}>-1</button>
        <button onClick={(e) => this.subNumber(5)}>-5</button>
        <button onClick={(e) => this.subNumber(8)}>-8</button>
      </div>
    );
  }
}

export default Profile;

**使用react-redux **

https://cn.react-redux.js.org/introduction/getting-started

npm insatll react-redux

connect

// 在  src/index.js 中 引入react-redux的Provider
import { Provider } from 'react-redux';
import store from './store';


  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,

// 新建 一个组件 src/pages/About.jsx
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';

import { addNumberAction, subNumberAction } from '../store/actionCreators';

export class About extends PureComponent {
  caclNumber(num, isAdd) {
    if (isAdd) {
      console.log('+', num);
      this.props.addNumber(num);
    } else {
      console.log('-', num);
      this.props.subNumber(num);
    }
  }
  render() {
    const { counter } = this.props;
    return (
      <div>
        <h1>About: counter : {counter}</h1>

        <button onClick={(e) => this.caclNumber(6, true)}>+6</button>
        <button onClick={(e) => this.caclNumber(88, true)}>+88</button>
        <button onClick={(e) => this.caclNumber(3, false)}>-3</button>
        <button onClick={(e) => this.caclNumber(88, false)}>-88</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({ counter: state.counter });
const mapDiapatchToProps = (dispatch) => ({
  addNumber: (num) => dispatch(addNumberAction(num)),
  subNumber: (num) => dispatch(subNumberAction(num)),
});
// connect 返回一个高阶组件 
export default connect(mapStateToProps, mapDiapatchToProps)(About);

Redux的异步操作

  • 在之前简单的案例中,redux中保存的counter是一个本地定义的数据
    • 口 我们可以直接通过同步的操作来dispatch action, state就会被立即更新。
    • 口 但是真实开发中,redux中保行的很多数据可能来自服务器,我们需要进行异步的请求,再将数据保存到redux中。
  • 在之前学习网络请求的时候我们讲过,网络请求可以在class组件的componentDidMount中发送,所以我们可以有这样的结构:

在这里插入图片描述

  • 上面的代码有一个缺陷

    • 口 我们必须将网络请求的异步代码放到组件的生命周期中来完成;
    • 事实上,网络请求到的数据也属于我们状态管理的一部分,更好的一种方式应该是将其也交给redux来管理;

在这里插入图片描述

  • 但是在redux中如何可以进行异步的操作?

    • 答案就是使用 中间件(Middleware)Redux-thunk
    • Middlewarek可以帮助我们在请求和响应之间嵌入一些操作的代码。

理解中间件

  • redux也引入了中间件(Middlleware)的概念:
    • 口 这个中间件的目的是在dispatch的action和最终达到的reducer之间,扩展一些自己的代码;
    • 口 比如:日志记录、调用异步接口、添加代码调试功能等等;
  • 我们现在要做的事情就是发送异步的网络请求,所以我们可以添加对应的中间件;
    • 口 这里官网推荐的、包括演示的网络请求的中间件是使用 redux-thunk;
  • redux-thunk 是如何做到让我们可以发送异步的请求呢
    • 口 我们知道,默认情况下的dispatch(action),action需要是一个JavaScript的对象
    • 口 redux-thunk 可以让 dispatch(action函数),action 可以是一个函数;
    • 口 该函数会被调用,并且会传给这个函数一个dispatch函数和getState函数
    • dispatch函数用于我们之后再次派发action;
    • getState函数考虑到我们之后的一些操作需要依赖原来的状态,用于让我们可以获取之前的一些状态;

如何使用redux-thunk

  • 1.安装 redux-thunk yarn add redux-thunk

  • 2.在创建store时传入应用了middleware的enhance函数

    • 口 通过applyMiddleware来结合多个Middleware, 返回一个enhancer;

    • 口 将enhancer作为第二个参数传入到createStore中;

      const enhancer = applyMiddleware(thunk);
      const store = createStore(reducer,enhancer );
      
  • 3.定义返回一个函数的action

    • 口 注意:这里不是返回一个对象了,而是一个函数;

    • 口 该函数在dispatch之后会被执行:

      export const fetchCateMultiDataAction = () => {
        // 如果是一个普通action,返回一个action对象
        // 问题: 对象中是不能直接拿到从服务器请求的数据
        return function (dispatch, getState) {
          // 异步操作:网络请求
          console.log(getState());
          axios.get('http://123.207.32.32:8000/home/multidata').then((res) => {
            console.log(res.data);
            const banners = res.data.data.banner.list;
            const recommends = res.data.data.recommend.list;
      
            dispatch(changeBannerAction(banners));
            dispatch(changeRecommendAction(recommends));
          });
        };
      

redux-devtools

react-devtools

React 开发者工具 https://zh-hans.react.dev/learn/react-developer-tools

chrome

redux-devtool

Redux DevTools https://cn.redux.js.org/tutorials/fundamentals/part-4-store/#redux-devtools

Chrome

reducer的模块拆分

Reducer文件拆分
  • 自前我们己经将不同的状态处理拆分到不同的reducer中,我们来思考:
    • 口 虽然已经放到不同的函数了,但是这些函数的处理依然是在同一个文件中,代码非常的混乱:
    • 口 另外关于reducer中用到的constant、 action等我们也依然是在同一个文件巾;

在这里插入图片描述

combineReducers函数
  • 目前我们合并的方式是通过每次调用reducer函数自己来返回一个新的对象。

  • 事实上,redux给我们提供了一个combineReducers函数可以方便的让我们对多个reducer进行合并

// 将reducer合并
const reducer = combineReducers({
  counter: counterReducer,
  home: homeReducer,
});
  • 那么combineReducers是如何实现的呢?

    • 口 事实上,它也是将我们传入的reducers合并到一个对象中,最终返回一个combination的函数(相当于我们之前的reducer函数了);
    • 口 在执行combination函数的过程中,它会通过判断前后返回的数据是否相同来决定返回之前的state还是新的state;
    • 新的state会触发订阅者发生对应的刷新,而旧的state可以有效的组织订阅者发生刷新;
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起伏羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值