第7天:redux

  • 以下代码示例的参考代码只提供源码文件夹/src目录下的文件。
  • 静态资源文件夹因为都一样,所以就不提供了,可以点击这里下载public目录
  • *代码的使用:根据步骤3.1.2执行完之后,替换掉相关文件夹即可。

7.1. redux理解

7.1.1. 学习文档

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

7.1.2. redux是什么

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

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

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

7.1.4. redux工作流程

7.2. redux的三个核心概念

7.2.1. action

  1. 动作的对象
  2. 包含2个属性
    • type:标识属性, 值为字符串, 唯一, 必要属性
    • data:数据属性, 值类型任意, 可选属性
  3. 例子:
    { type: 'ADD_STUDENT',data:{name: 'tom',age:18} }

7.2.2. reducer

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

7.2.3. store

  1. stateactionreducer联系在一起的对象

  2. 如何得到此对象?
    1) import {createStore} from 'redux'
    2) import reducer from './reducers'
    3) const store = createStore(reducer)

  3. 此对象的功能?
    1) getState(): 得到state
    2) dispatch(action): 分发action, 触发reducer调用, 产生新的state
    3) subscribe(listener): 注册监听, 当产生了新的state时, 自动调用

7.3. redux的核心API

7.3.1. createstore()

作用:创建包含指定reducerstore对象

7.3.2. store对象

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

7.3.3. applyMiddleware()

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

7.3.4. combineReducers()

作用:合并多个reducer函数

7.4. 使用redux编写应用

redux精简版
  • src/App.jsx

    import React, { Component } from 'react'
    import Count from './components/Count'
    //
    export default class App extends Component {
    render() {
        return (
            <div>
                <Count/>
            </div>
        )
    }
    }
  • src/index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    import store from './redux/store'
    //
    ReactDOM.render(<App/>,document.getElementById('root'))
    //
    store.subscribe(()=>{
    ReactDOM.render(<App/>,document.getElementById('root'))
    })
  • src/components/Count/index.jsx

    import React, { Component } from 'react'
    //引入store,用于获取redux中保存状态
    import store from '../../redux/store'
    //
    export default class Count extends Component {
    
    state = {carName:'BCc63'}
    
    /* componentDidMount(){
        //检测redux中状态的变化,只要变化,就调用render
        store.subscribe(()=>{
            this.setState({})
        })
    } */
    
    //加法
    increment = ()=>{
        const {value} = this.selectNumber
        store.dispatch({type:'increment',data:value*1})
    }
    //减法
    decrement = ()=>{
        const {value} = this.selectNumber
        store.dispatch({type:'decrement',data:value*1})
    }
    //奇数再加
    incrementIfOdd = ()=>{
        const {value} = this.selectNumber
        const count = store.getState()
        if(count % 2 !== 0){
            store.dispatch({type:'increment',data:value*1})
        }
    }
    //异步加
    incrementAsync = ()=>{
        const {value} = this.selectNumber
        setTimeout(()=>{
            store.dispatch({type:'increment',data:value*1})
        },500)
    }
    
    render() {
        return (
            <div>
                <h1>当前求和为:{store.getState()}</h1>
                <select ref={c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> 
                <button onClick={this.increment}>+</button> 
                <button onClick={this.decrement}>-</button> 
                <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button> 
                <button onClick={this.incrementAsync}>异步加</button> 
            </div>
        )
    }
    }
  • src/redux/count_reducer.js

    //1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
    //2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
    //
    const initState = 0 //初始化状态
    export default function countReducer(preState=initState,action){
    // console.log(preState);
    //从action对象中获取:type、data
    const {type,data} = action
    //根据type决定如何加工数据
    switch (type) {
        case 'increment': //如果是加
            return preState + data
        case 'decrement': //若果是减
            return preState - data
        default:
            return preState
    }
    }
  • src/redux/store.js

    //该文件专门用于暴露一个store对象,整个应用只有一个store对象
    //
    //引入createStore,专门用于创建redux中最为核心的store对象
    import {createStore} from 'redux'
    //引入为Count组件服务的reducer
    import countReducer from './count_reducer'
    //暴露store
    export default createStore(countReducer)

7.5. redux异步编程

7.5.1理解:

  1. redux默认是不能进行异步处理的,
  2. 某些时候应用中需要在redux中执行异步任务(ajax, 定时器)

7.5.2. 使用异步中间件

npm install --save redux-thunk

7.6. react-redux

7.6.1. 理解

  1. 一个react插件库
  2. 专门用来简化react应用中使用redux

7.6.2. react-Redux将所有组件分成两大类

  1. UI组件
    1) 只负责 UI 的呈现,不带有任何业务逻辑
    2) 通过props接收数据(一般数据和函数)
    3) 不使用任何 Redux 的 API
    4) 一般保存在components文件夹下
  2. 容器组件
    1) 负责管理数据和业务逻辑,不负责UI的呈现
    2) 使用 Redux 的 API
    3) 一般保存在containers文件夹下

7.6.3. 相关API

  1. Provider:让所有组件都可以得到state数据

    <Provider store={store}>
    <App />
    </Provider>
  2. connect:用于包装 UI 组件生成容器组件

    import { connect } from 'react-redux'
    connect(
    mapStateToprops,
    mapDispatchToProps
    )(Counter)
  3. mapStateToprops:将外部的数据(即state对象)转换为UI组件的标签属性

    const mapStateToprops = function (state) {
    return {
    value: state
    }
    }
  4. mapDispatchToProps:将分发action的函数转换为UI组件的标签属性

7.7. 使用上redux调试工具

7.7.1. 安装chrome浏览器插件

7.7.2. 下载工具依赖包

npm install --save-dev redux-devtools-extension

7.8. 纯函数和高阶函数

7.8.1. 纯函数

  1. 一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)
  2. 必须遵守以下一些约束
    1) 不得改写参数数据
    2) 不会产生任何副作用,例如网络请求,输入和输出设备
    3) 不能调用Date.now()或者Math.random()等不纯的方法
  3. redux的reducer函数必须是一个纯函数

7.8.2. 高阶函数

  1. 理解: 一类特别的函数
    1) 情况1: 参数是函数
    2) 情况2: 返回是函数
  2. 常见的高阶函数:
    1) 定时器设置函数
    2) 数组的forEach()/map()/filter()/reduce()/find()/bind()
    3) promise
    4) react-redux中的connect函数
  3. 作用: 能实现更加动态, 更加可扩展的功能

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注