《React后台管理系统实战:九》Redux原理:小功能实现(一)

49 篇文章 6 订阅

前端常用:https://docschina.org/

1.redux基础

1.1 学习文档

  1. 英文文档: https://redux.js.org/
  2. 中文文档: https://cn.redux.js.org/
  3. Github: https://github.com/reactjs/redux

1.2. redux 是什么?

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

1.3. redux 工作流程

react流程
在这里插入图片描述

[ 问题 ]

在React中,数据在组件中是单向流动的,数据从一个方向父组件流向子组件(通过props),所以,两个非父子组件之间通信就相对麻烦,redux的出现就是为了解决state里面的数据问题在React中,数据在组件中是单向流动的,数据从一个方向父组件流向子组件(通过props),所以,两个非父子组件之间通信就相对麻烦,redux的出现就是为了解决state里面的数据问题

[ 解决 ]

Redux是将整个应用状态存储到一个地方上称为store,里面保存着一个状态树store tree,组件可以派发(dispatch)行为(action)给store,而不是直接通知其他组件,组件内部通过订阅store中的状态state来刷新自己的视图。

Redux三大原则

  1. 唯一数据源
  2. 保持只读状态
  3. 数据改变只能通过纯函数来执行
1.唯一数据源:

整个应用的state都被存储到一个状态树里面,并且这个状态树,只存在于唯一的store中。

2.保持只读状态:

state是只读的,唯一改变state的方法就是触发action,action是一个用于描述以发生时间的普通对象。

3.数据改变只能通过纯函数来执行:

使用纯函数来执行修改,为了描述action如何改变state的,需要编写reducers。

1.4. 什么情况下需要使用 redux

  1. 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
  2. 某个组件的状态,需要共享
  3. 某个状态需要在任何地方都可以拿到
  4. 一个组件需要改变全局状态
  5. 一个组件需要改变另一个组件的状态

2. redux 的核心 API

2.1. createStore()

  1. 作用:创建包含指定 reducer 的 store 对象
  2. 编码:
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)

2.2. store 对象

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

2.3. applyMiddleware()

  1. 作用:
    应用上基于 redux 的中间件(插件库)
  2. 编码:
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk' // redux 异步中间件
const store = createStore(
counter,
applyMiddleware(thunk) // 应用上异步中间件
)

2.4. combineReducers()

  1. 作用: 合并多个 reducer 函数
  2. 编码:
export default combineReducers({
user,
chatUser,
chat
})

3. redux 的三个核心概念

3.1. action

  1. 标识要执行行为的对象
  2. 包含 2 个方面的属性
    a. type: 标识属性, 值为字符串, 唯一, 必要属性
    b. xxx: 数据属性, 值类型任意, 可选属性
  3. 例子:
const action = {
type: 'INCREMENT',
data: 2
}
  1. Action Creator(创建 Action 的工厂函数)
const increment = (number) => ({type: 'INCREMENT', data: number})

3.2. reducer

  1. 根据老的 state 和 action, 产生新的 state 的纯函数
  2. 样例
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + action.data
case 'DECREMENT':
return state - action.data
default:
return state
}
}
  1. 注意
    a. 返回一个新的状态
    b. 不要修改原来的状态

3.3. store

  1. 将 state,action 与 reducer 联系在一起的对象
  2. 如何得到此对象?
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
  1. 此对象的功能?
getState() : 得到 state
dispatch(action) : 分发 action, 触发 reducer 调用, 产生新的 state
subscribe(listener) : 注册监听, 当产生了新的 state 时, 自动调用

4. 安装 redux

1. 进入项目目录安装redux

cnpm install --save redux

5.react版本的状态使用实战

1.新建一个git 分支并切换进去

git checkout -b redux

2.把原src改成别的名字如src_app

3.新建一个src在里面写基础的index.js app.jsx

index.js

import React from 'react' 
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App/>,document.getElementById('root'))

未用redux实现的app.jsx

import React,{Component} from 'react'

export default class App extends Component{
    state = {
        count: 0
      }


    constructor(props) {
    super(props)
    this.numberRef = React.createRef() //【1】创建一个ref
    }


    //自加
    increment = () => {
        const number = this.numberRef.current.value * 1 //【3】引用ref处的当前值
        this.setState(state => ({count: state.count + number}))
    }

    //自减
    decrement = () => {
        const number = this.numberRef.current.value * 1
        this.setState(state => ({count: state.count - number}))
      }
    
      //如果当前是奇数就进行自加
      incrementIfOdd = () => {
        const number = this.numberRef.current.value * 1
        if (this.state.count % 2 === 1) {
          this.setState(state => ({count: state.count + number}))
        }
    
      }

      //异步自加,此处用隔一秒加模拟异步
      incrementAsync = () => {
        const number = this.numberRef.current.value * 1
        setTimeout(() => {
          this.setState(state => ({count: state.count + number}))
        }, 1000)
      }

    render(){
        const count = this.state.count
        return(
            <div>
                <p>click {count} times</p>
                <select ref={this.numberRef}> {/**【2】使用ref */}
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> &nbsp;&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
                <button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}

效果:http://localhost:3000/

  1. 自加
  2. 自减
  3. 是5处为奇数时才会加
  4. 过一秒再加(模拟异步)

在这里插入图片描述

6.redux版本的状态管理实战(一:读取)

1.复制一份src备份一下

2.在src下建一个文件夹和文件:redux/store.js

// redux最核心的管理对象: store
import {createStore} from 'redux'
import reducer from './reducer' //【1】导入reducer

export default createStore(reducer) // 【2】创建store对象内部会第一次调用reducer()得到初始状态值

3.新建文件:src/redux/reducer.js

// reducer函数模块: 根据当前state和指定action返回一个新的state

// 管理count状态数据的reducer
export default function count(state=1,action){ //state=1初始化state的值,
    console.log('count()的state和action分别是:',state,action)  //看看都是些啥
    switch(action.type){
        case 'INCREMENT' :
            return state+action.data //data取决于action.js里的返回对象
        case 'DECREMENT':
            return state-action.data 
        default: 
        //都不是就默认就返回state【重点是在这里因为action还未写,上面两步case无效】
            return state
    }
}

4.到index.js

import React from 'react' 
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store' //【1】导入store

//【2】传store给App子组件
ReactDOM.render(<App store={store} />,document.getElementById('root'))

5.到App.js

【0】-【3】
注意:此时各函数都无法使用,因为它调用的还是之前的状态

import React,{Component} from 'react'
import PropTypes from 'prop-types' //【0】引入propTypes

export default class App extends Component{
    /*state = { //【1】关闭state
        count: 0
      }*/
    
    //【2】接收store--前一步转index.js传一个store过来
    static propTypes={
        store:PropTypes.object.isRequired
    }


    constructor(props) {
    super(props)
    this.numberRef = React.createRef() //创建一个ref
    }


    //自加
    increment = () => {
        const number = this.numberRef.current.value * 1 //引用ref处的当前值
        this.setState(state => ({count: state.count + number}))
    }

    //自减
    decrement = () => {
        const number = this.numberRef.current.value * 1
        this.setState(state => ({count: state.count - number}))
      }
    
      //如果当前是奇数就进行自加
      incrementIfOdd = () => {
        const number = this.numberRef.current.value * 1
        if (this.state.count % 2 === 1) {
          this.setState(state => ({count: state.count + number}))
        }
    
      }

      //异步自加,此处用隔一秒加模拟异步
      incrementAsync = () => {
        const number = this.numberRef.current.value * 1
        setTimeout(() => {
          this.setState(state => ({count: state.count + number}))
        }, 1000)
      }

    render(){
        //【3】得到store的状态,此时应该显示1
        const count = this.props.store.getState()
        return(
            <div>
                <p>click {count} times</p>
                <select ref={this.numberRef}> {/**使用ref */}
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> &nbsp;&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
                <button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}

效果:此时的状态由reducer.js里state控制,变成1

控制台变:count()的state和action分别是: 1 {type: “@@redux/INITs.m.l.t.8”}
在这里插入图片描述

7.redux版本状态管理(二、操作state)

1.新建redux/action-types.js用于存放动作名变量防止写错

//包含n个action type常量名称的模块
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

2.新建actions.js用于存放动作

//【0】包含n个用来创建action的工厂函数(action creator)
import {INCREMENT, DECREMENT} from './action-types'

/*普通写法export function increment(number){
    return {type: INCREMENT, data: number}
}*/

//【1】增加的action
export const increment = number => ({type: INCREMENT, data: number}) //返回对象别忘记加括号
//【2】减少action
export const decrement = number => ({type: DECREMENT, data: number})

3.reducer.js(action实际存放处:用于操作状态)

// reducer函数模块: 根据当前state和指定action返回一个新的state
import {INCREMENT, DECREMENT} from './action-types'

// 管理count状态数据的reducer
export default function count(state=1,action){ //state=1初始化state的值,
    console.log('count()的state和action分别是:',state,action)  //看看都是些啥
    switch(action.type){
        case INCREMENT :
            return state + action.data //data取决于action.js里的返回对象
        case DECREMENT:
            return state - action.data 
        default:        //都不是就默认就返回state
            return state
    }
}

4. app.js修改各函数来操作状态(重点)

import React,{Component} from 'react'
import PropTypes from 'prop-types' //引入propTypes
import {increment,decrement} from './redux/actions' //引入动作

export default class App extends Component{
    
    //接收store--前一步转index.js传一个store过来
    static propTypes={
        store:PropTypes.object.isRequired
    }


    constructor(props) {
      super(props)
      this.numberRef = React.createRef() //创建一个ref
    }


    //自加 increment
    increment = () => {
        const number = this.numberRef.current.value * 1 //引用ref处的当前值
        // this.setState(state => ({count: state.count + number}))
        this.props.store.dispatch(increment(number))  //【1】改变状态也可写成这样,但正常是单独写个动作放acions.js里 dispatch({type:'INCREMENT',data:number})
    }

    //自减
    decrement = () => {
        const number = this.numberRef.current.value * 1
        this.props.store.dispatch(decrement(number)) //【2】同上
      }
    
      //如果当前是奇数就进行自加
      incrementIfOdd = () => {
        const number = this.numberRef.current.value * 1
        if (this.props.store.getState() % 2 === 1) {
          this.props.store.dispatch(increment(number)) //【3】同上
        }
    
      }

      //异步自加,此处用隔一秒加模拟异步
      incrementAsync = () => {
        const number = this.numberRef.current.value * 1
        setTimeout(() => {
          this.props.store.dispatch(increment(number)) //【4】同上
        }, 1000)
      }

    render(){
        //得到store的状态,此时应该显示1
        const count = this.props.store.getState()
        return(
            <div>
                <p>click {count} times</p>
                <select ref={this.numberRef}> {/**使用ref */}
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> &nbsp;&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;&nbsp;
                <button onClick={this.incrementIfOdd}>increment if odd</button>&nbsp;&nbsp;
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}

5.index.js添加监听store内部的状态数据发生改变时回调

import React from 'react' 
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store' //导入store

//传store给App子组件
ReactDOM.render(<App store={store} />,document.getElementById('root'))

//【1】给store绑定状态更新的监听
store.subscribe(() => { // store内部的状态数据发生改变时回调
    // 重新渲染App组件标签
    ReactDOM.render(<App store={store} />, document.getElementById('root'))
})

6.store.js(附)

// redux最核心的管理对象: store,
import {createStore} from 'redux'
import reducer from './reducer' //【1】导入reducer

export default createStore(reducer) // 【2】创建store对象内部会第一次调用reducer()得到初始状态值

7.效果:同5.3,控制台输出:

在这里插入图片描述

count()的state和action分别是: 1 {type: "@@redux/INITq.p.n.h.i"}
reducer.js:6 count()的state和action分别是: 1 {type: "increment", data: 1}
reducer.js:6 count()的state和action分别是: 2 {type: "increment", data: 1}
reducer.js:6 count()的state和action分别是: 3 {type: "increment", data: 1}
reducer.js:6 count()的state和action分别是: 4 {type: "increment", data: 1}
reducer.js:6 count()的state和action分别是: 5 {type: "increment", data: 1}
reducer.js:6 count()的state和action分别是: 6 {type: "decrement", data: 1}
reducer.js:6 count()的state和action分别是: 5 {type: "increment", data: 1}

8.总结流程

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值