第八章:redux

第八章:redux

8.1. redux 理解

8.1.1. 学习文档

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

  2. 中文文档: http://www.redux.org.cn/

  3. Github: https://github.com/reactjs/redux

8.1.2. redux 是什么?

  1. redux 是一个独立专门用于做状态管理的 JS 库(不是 react 插件库)

  2. 它可以用在 react, angular,vue 等项目中, 但基本与 react 配合使用

  3. 作用: 集中式管理 react 应用中多个组件共享的状态

8.1.3. redux

image-20201116143828824

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

  1. 总体原则: 能不用就不用, 如果不用比较吃力才考虑使用

  2. 某个组件的状态,需要共享

  3. 某个状态需要在任何地方都可以拿到

  4. 一个组件需要改变全局状态

  5. 一个组件需要改变另一个组件的状态

8.2. redux 的核心 API

8.2.1. createStore()

  1. 作用:

创建包含指定 reducer 的 store 对象

  1. 编码:
import {createStore} from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)

8.2.2. store 对象

  1. 作用:

redux 库最核心的管理对象

  1. 它内部维护着:

state
reducer

  1. 核心方法:
    getState()
    dispatch(action)
    subscribe(listener)
  2. 编码:
store.getState()
store.dispatch({type:'INCREMENT', number})
store.subscribe(render)

8.2.3. applyMiddleware()

  1. 作用:

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

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

8.2.4. combineReducers()

  1. 作用:

合并多个 reducer 函数

  1. 编码:
export default combineReducers({
    user,
    chatUser,
    chat
})

8.3. redux 的三个核心概念

8.3.1. action

  1. 标识要执行行为的对象

  2. 包含 2 个方面的属性

a. type: 标识属性, 值为字符串, 唯一, 必要属性

b. xxx: 数据属性, 值类型任意, 可选属性

  1. 例子:
const action = {
    type: 'INCREMENT',
    data: 2
}
  1. Action Creator(创建 Action 的工厂函数)
const increment = (number) => ({type: 'INCREMENT', data: number})

8.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. 不要修改原来的状态

8.3.3. store

  1. 将 state,action 与 reducer 联系在一起的对象

  2. 如何得到此对象?

import {createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
  1. 此对象的功能?

getState(): 得到 state

dispatch(action): 分发 action, 触发 reducer 调用, 产生新的 state

subscribe(listener): 注册监听, 当产生了新的 state 时, 自动调用

8.4. 使用 redux 编写应用

8.4.1. 效果

8.4.2. 下载依赖包

npm install --save redux

8.4.3. redux/action-types.js

/*
action 对象的 type 常量名称模块
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

8.4.4. redux/actions.js

/*
action creator 模块
*/
import {INCREMENT, DECREMENT} from './action-types'
export const increment = number => ({type: INCREMENT, number})
export const decrement = number => ({type: DECREMENT, number})

8.4.5. redux/reducers.js

/*
根据老的 state 和指定 action, 处理返回一个新的 state
*/
import {INCREMENT, DECREMENT} from '../constants/ActionTypes'
import {INCREMENT, DECREMENT} from './action-types'
export function counter(state = 0, action) {
    console.log('counter', state, action)
    switch (action.type) {
        case INCREMENT:
            return state + action.number
        case DECREMENT:
            return state - action.number
        default:
            return state
    }
}

8.4.6. components/app.jsx

/*
应用组件
*/
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import * as actions from '../redux/actions'
export default class App extends Component {
    static propTypes = {
        store: PropTypes.object.isRequired,
    }
    increment = () => {
        const number = this.refs.numSelect.value * 1
        this.props.store.dispatch(actions.increment(number))
    }
    decrement = () => {
        const number = this.refs.numSelect.value * 1
        this.props.store.dispatch(actions.decrement(number))
    }
    incrementIfOdd = () => {
        const number = this.refs.numSelect.value * 1
        let count = this.props.store.getState()
        if (count % 2 === 1) {
            this.props.store.dispatch(actions.increment(number))
        }
    }
    incrementAsync = () => {
        const number = this.refs.numSelect.value * 1
        setTimeout(() => {
            this.props.store.dispatch(actions.increment(number))
        }, 1000)
    }
    render() {
        return (
            <div>
                <p>
                    click {this.props.store.getState()} times {' '}
                </p>
                <select ref="numSelect">
                    <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}>increment if odd</button>
                {' '}
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}

8.4.7. index.js

import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import App from './components/app'
import {counter} from './redux/reducers'
// 根据 counter 函数创建 store 对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
const render = () => {
    ReactDOM.render(
        <App store={store}/>,
    	document.getElementById('root')
    )
}
// 初始化渲染
render()
// 注册 ( 订阅 ) 监听 , 一旦状态发生改变 , 自动重新渲染
store.subscribe(render)

8.4.8. 问题

  1. redux 与 react 组件的代码耦合度太高

  2. 编码不够简洁

8.5. react-redux

8.5.1. 理解

  1. 一个 react 插件库

  2. 专门用来简化 react 应用中使用 redux

8.5.2. React-Redux 将所有组件分成两大类

  1. UI 组件

a. 只负责 UI 的呈现,不带有任何业务逻辑

b. 通过 props 接收数据(一般数据和函数)

c. 不使用任何 Redux 的 API

d. 一般保存在 components 文件夹下

  1. 容器组件

a. 负责管理数据和业务逻辑,不负责 UI 的呈现

b. 使用 Redux 的 API

c. 一般保存在 containers 文件夹下

8.5.3. 相关 API

  1. Provider

让所有组件都可以得到 state 数据

<Provider store={store}>
    <App />
</Provider>
  1. connect()

用于包装 UI 组件生成容器组件

import { connect } from 'react-redux'
connect(
    mapStateToprops,
    mapDispatchToProps
)(Counter)
  1. mapStateToprops()

将外部的数据(即 state 对象)转换为 UI 组件的标签属性

const mapStateToprops = function (state) {
    return {
        value: state
    }
}
  1. mapDispatchToProps()

将分发 action 的函数转换为 UI 组件的标签属性

简洁语法可以直接指定为 actions 对象或包含多个 action 方法的对象

8.5.4. 使用 react-redux

  1. 下载依赖包

npm install --save react-redux

  1. redux/action-types.js

不变

  1. redux/actions.js

不变
4) redux/reducers.js

不变

  1. components/counter.jsx
/*
UI 组件 : 不包含任何 redux API
*/
import React from 'react'
import PropTypes from 'prop-types'
export default class Counter extends React.Component {
    static propTypes = {
        count: PropTypes.number.isRequired,
        increment: PropTypes.func.isRequired,
        decrement: PropTypes.func.isRequired
    }
    increment = () => {
        const number = this.refs.numSelect.value * 1
        this.props.increment(number)
    }
    decrement = () => {
        const number = this.refs.numSelect.value * 1
        this.props.decrement(number)
    }
    incrementIfOdd = () => {
        const number = this.refs.numSelect.value * 1
        let count = this.props.count
        if (count % 2 === 1) {
            this.props.increment(number)
        }
    }
    incrementAsync = () => {
        const number = this.refs.numSelect.value * 1
        setTimeout(() => {
            this.props.increment(number)
        }, 1000)
    }
    render() {
        return (
            <div>
                <p>
                    click {this.props.count} times {' '}
                </p>
                <select ref="numSelect">
                    <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}>increment if odd</button>
                {' '}
                <button onClick={this.incrementAsync}>increment async</button>
            </div>
        )
    }
}
  1. containters/app.jsx
/*
包含 Counter 组件的容器组件
*/
import React from 'react'
// 引入连接函数
import {connect} from 'react-redux'
// 引入 action 函数
import {increment, decrement} from '../redux/actions'
import Counter from '../components/counter'
// 向外暴露连接 App 组件的包装组件
export default connect(
    state => ({count: state}),
    {increment, decrement}
)(Counter)
  1. index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import App from './containers/app'
import {counter} from './redux/reducers'
// 根据 counter 函数创建 store 对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
ReactDOM.render(
    (
        <Provider store={store}>
        	<App />
        </Provider>
	),
    document.getElementById('root')
);

8.5.5. 问题

  1. redux 默认是不能进行异步处理的,

  2. 应用中又需要在 redux 中执行异步任务(ajax, 定时器)

8.6. redux 异步编程

8.6.1. 下载 redux 插件( 异步中间件)

npm install --save redux-thunk

8.6.2. index.js

import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
// 根据 counter 函数创建 store 对象
const store = createStore(
    counter,
    applyMiddleware(thunk) // 应用上异步中间件
)

8.6.3. redux/actions.js

// 异步 action creator( 返回一个函数 )
export const incrementAsync = number => {
    return dispatch => {
        setTimeout(() => {
            dispatch(increment(number))
        }, 1000)
    }
}

8.6.4. components/counter.jsx

incrementAsync = () => {
    const number = this.refs.numSelect.value*1
    this.props.incrementAsync(number)
}

8.6.5. containers/app.jsx

import {increment, decrement, incrementAsync} from '../redux/actions'
// 向外暴露连接 App 组件的包装组件
export default connect(
    state => ({count: state}),
    {increment, decrement, incrementAsync}
)(Counter)

8.7. 使用上 redux 调试工具

8.7.1. 安装 chrome 浏览器插件

redux-devtools

8.7.2. 下载工具依赖包

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

8.7.3. 编码

import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(
    counter,
    composeWithDevTools(applyMiddleware(thunk))
)

8.8. 相关重要知识: 纯函数和高阶函数

8.8.1. 纯函数

  1. 一类特别的函数: 只要是同样的输入,必定得到同样的输出

  2. 必须遵守以下一些约束

a. 不得改写参数

b. 不能调用系统 I/O 的 API

c. 能调用 Date.now()或者 Math.random()等不纯的方法

  1. reducer 函数必须是一个纯函数

8.8.2. 高阶函数

  1. 理解: 一类特别的函数

a. 情况 1: 参数是函数

b. 情况 2: 返回是函数

  1. 常见的高阶函数:

a. 定时器设置函数

b. 数组的 map()/filter()/reduce()/find()/bind()

c. react-redux 中的 connect 函数

  1. 作用:

a. 能实现更加动态, 更加可扩展的功能

8.7.3. 编码

import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(
    counter,
    composeWithDevTools(applyMiddleware(thunk))
)

8.8. 相关重要知识: 纯函数和高阶函数

8.8.1. 纯函数

  1. 一类特别的函数: 只要是同样的输入,必定得到同样的输出

  2. 必须遵守以下一些约束

a. 不得改写参数

b. 不能调用系统 I/O 的 API

c. 能调用 Date.now()或者 Math.random()等不纯的方法

  1. reducer 函数必须是一个纯函数

8.8.2. 高阶函数

  1. 理解: 一类特别的函数

a. 情况 1: 参数是函数

b. 情况 2: 返回是函数

  1. 常见的高阶函数:

a. 定时器设置函数

b. 数组的 map()/filter()/reduce()/find()/bind()

c. react-redux 中的 connect 函数

  1. 作用:

a. 能实现更加动态, 更加可扩展的功能

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码小余の博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值