0
点赞
收藏
分享

微信扫一扫

一文带你了解redux的工作流程——action/reducer/store

自信的姐姐 2022-07-27 阅读 75

文章目录

在这里插入图片描述

redux

redux理解

英文文档:https://redux.js.org/

中文文档:https://www.redux.org.cn/

Github:https://github.com/reduxjs/redux

redux是什么

  1. redux是一个专门用于做状态管理的JS库(不是react插件库)。
  2. 它可以用在react,angular,vue等项目中,但基本与react配合使用。
  3. 作用:集中式管理react应用中多个组件共享的状态。

什么情况下需要使用redux

  1. 某个组件的状态,需要让其他组件可以随时拿到共享)。
  2. 一个组件需要改变另一个组件的状态(通信)。
  3. 总体原则:能不用就不用,如果不用比较吃力才考虑使用。

redux工作流程

在这里插入图片描述

redux的三个核心概念

🔥action

1️⃣ 动作的对象
2️⃣ 包含2个属性

  • type:标识属性,值为字符串,唯一,必要属性
  • data:数据属性,值类型任意,可选属性

3️⃣ 例子:{type:‘ADD_STUDENT’,data:{name:‘tom’,age:18} }

🔥reducer

1️⃣ 用于初始化状态加工状态
2️⃣ 加工时,根据旧的stateaction,产生新的state的纯函数

🔥store

1️⃣ 将state、action、reducer联系在一起的对象
2️⃣ 如何得到此对象?

  • import {createStore} from ‘redux’
  • import reducer from ‘./reducers’
  • const store = createStore(reducer)

3️⃣ 此对象的功能?

  • getState(): 得到state
  • dispatch(action): 分发action, 触发reducer调用, 产生新的state
  • subscribe(listener): 注册监听, 当产生了新的state时, 自动调用

redux的核心API

🔥createstore()

作用:创建包含指定reducer的store对象

🔥store对象

  1. 作用:redux库最核心的管理对象
  2. 它内部维护着:
    • state
    • reducer
  3. 核心方法:
    • getState()
    • dispatch(action)
    • subscribe(listener)
  4. 具体编码:
    • store.getState()
    • store.dispatch({type:‘INCREMENT’,number})
    • store.subscribe(render)

🔥applyMiddleware()

作用:应用上基于redux的中间件(插件库)

🔥combineReducers()

作用:合并多个reducer函数

使用redux编写应用

📝案例需求

效果:

✏️原生react版写法

Count组件 => index.jsx:

import React, { Component } from 'react'

export default class Count extends Component {

  state = {
    count: 0
  }

  // 加法
  increment = () => {
    // 获取用户输入
    const { value } = this.selectNumber
    // 读取原来的状态值
    const { count } = this.state
    this.setState({ count: count + value * 1 })
  }

  // 减法
  decrement = () => {
    // 获取用户输入
    const { value } = this.selectNumber
    // 读取原来的状态值
    const { count } = this.state
    this.setState({ count: count - value * 1 })
  }

  // 奇数再加
  incrementIfOdd = () => {
    // 获取用户输入
    const { value } = this.selectNumber
    // 读取原来的状态值
    const { count } = this.state
    if (count % 2 !== 0) {
      this.setState({ count: count + value * 1 })
    }
  }

  // 异步加
  incrementAsync = () => {
    // 获取用户输入
    const { value } = this.selectNumber
    // 读取原来的状态值
    const { count } = this.state
    setTimeout(() => {
      this.setState({ count: count + value * 1 })
    }, 500)
  }

  render() {
    return (
      <div>
        <h1>当前求和为:{this.state.count}</h1>
        <select ref={c => this.selectNumber = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>&nbsp;
        <button onClick={this.increment}>+</button>&nbsp;
        <button onClick={this.decrement}>-</button>&nbsp;
        <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
        <button onClick={this.incrementAsync}>异步加</button>
      </div>
    )
  }
}
举报

相关推荐

0 条评论