Redux的核心原理

为什么要使用redux?

随着互联网的高速发展,我们的应用变得越来越复杂,进行导致我们的组件之间的关系也变得日趋复杂,往往需要将状态父组件 -> 子组件 -> 子子组件 -> 又或者只是简单的 父组件与子组件之间的props传递也会导致我们的数据流变得难以维护,因为二次开发者不在熟悉项目的情况下无法第一时间确定数据来源是由谁发起的。使用redux之后,所有的状态都来自于store中的state,并且store通过react-redux中的Provider组件可以传递到Provider组件下的所有组件,也就是说store中的state对于Provider下的组件来说就是全局的。

redux的核心原理是什么

1.将应用的状态统一放到state中,由store来管理state。
2.reducer的作用是返回一个新的state去更新store中对用的state。
3.按redux的原则,UI层每一次状态的改变都应通过action去触发,action传入对应的reducer 中,reducer返回一个新的state更新store中存放的state,这样就完成了一次状态的更新
4.subscribe是为store订阅监听函数,这些订阅后的监听函数是在每一次dipatch发起后依次执行
5.可以添加中间件对提交的dispatch进行重写

redux的api有哪些

1.createStore 创建仓库,接受reducer作为参数
2.bindActionCreator 绑定store.dispatch和action 的关系
3.combineReducers 合并多个reducers
4.applyMiddleware 洋葱模型的中间件,介于dispatch和action之间,重写dispatch
5.compose 整合多个中间件

接下来我们来依次实现createStore、bindActionCreator、combineReducers、applyMiddleware、compose

createStore的实现

function createStore (reducer, enhancer) {
    if (enhancer) {
        enhancer(createStore)(reducer)
    }
    let currentState = {} //这就是前面提到的store管理的state
    let currentListener = [] //这是前面提到的为store添加监听函数
    
    function subscribe (func) {
        currentListener.push(func)
    }
    
    function getState () {
        return JSON.parse(JSON.stringify(state));
    }
 
    funtion dispatch (action) {
        currentState = reducer(currentState, action)
        currentListener.map(listen => listen()) //每当发生依次dispatch后都会遍历监听函数并执行
        return action
    }
 
    return {
        subscribe,
        getState,
        dispatch
    }
}

注意: createStore并没有直接返回store中存放的state,而是返回一个函数getState来获取state,当我们调用getState去获取state时,需要返回一个state的复制品,也就是需要返回一个深拷贝state之后对象,这样可以避免state值的非法篡改,因为如何直接返回state的话,只需通过state[key] = xxxx就能对state进行修改,违背了redux只能通过dispatch(action)去更新state

bindActionCreator的实现


function bindActionCreator (creators, dispatch) {
    let bound = {}
    Object.keys(creators).map(key =>{
        const creator = creators[key]
        bound[key] = (..args) => dispach(creator(...args))
    })
    return bound
}

bindActionCreator是为action函数外面包一层dispatch,这样在进行action发起时无需再手动dispatch了

combineReducers的实现


function combineReducers (reducers) {
    const reducersKeys = Object.keys(reducers),
    finalReducers = {}
    for (let i = 0; i < reducerKeys.length; i++) {
        if (typeof reducers[i] === 'function') {
            finalReducers[i] = reducers[i]
        }
    }
    const finalReducersKeys = Object.keys(finalReducers)
    return function combination (state={}, action) {
        let hasChanged = false,
            nextState = {}
        for (let i = 0; i < finalReducersKeys.length; i++) {
            const key = finalReducersKeys[i],
            reducer = finalReducers[key],
            preStateKeys = state[key],
            nextStateKeys = reducer(preState, action),
            nextState[key] = nextStateKeys
            hasChanged = hasChanged || preStateKeys !== nextStateKeys
        }
        return hasChanged ? nextState : state
    }
}

applyMiddleware的实现


function applyMiddleware (...middlewares) {
    return createStore => (...args) => {
        const store = createStore(...args)
        let { getState, dispatch } = store
        const middlewateApi = {
            getState,
            dispatch: (...args) => dispatch(...args)
        }
        const middlewareChain = middlewares.map(middleware => middlware(middlewareApi))
        dispatch = compose(...middlewareChanin)(dispatch)
        return {
            store,
            dispatch
        }
    }
}

compose的实现


function compose (...funcs) {
    if(funcs.length === 0) {
        return args => args
    }
    if (funcs.length === 1) {
        return funcs[0]
    }
    return funcs.reduce( (ret, item) => (...args) => ret(item(...args)) )
}

compose是整合多个中间件的情况,这里使用reduce对用传入的中间件进行累加执行

react-redux

为什么要使用react-redux?

回答这个问题,只需要明确我们的最终目的:能在react组件中实现对store中的state进行获取、修改、监听,而从上述内容可以知道,createStore会给我们返回getState、dispatch、subscribe来进行获取state、修改state、监听state变化,而我们现在要做的就是把这个三个函数传递给react组件就可以了,所以我们就需要react-redux来帮助我们

react-redux的核心原理是什么?

1.将Provider高阶组件包裹在组件的最外层,并且将创建的store传入Provider高阶组件中,
然后再Provider高阶组件内部获取传入的store并将它添加到Provider高阶组件的context上下文中,context是react组件特有的一种不用手动一层层传递props就能在组件树中传递数据的方式,这样就实现了store相对于react组件的全局化,所有组件都能对store进行修改,获取,监听了

2.虽然Provider下的组件都拥有可以操作store的能力了,但是由于倘若我们要在每一个组件都从context中去获取store会造成大量代码冗余,还有一点就是即使你能在react组件中能够操作store了,但是当你dispatch一个action之后,store中的state虽然更新了,但是并不会触发组件中的render函数去渲染新的数据,所以我们就需要通过react-redux另一个高阶组件connect
来做集中处理。connect组件接受一个component组件返回一个新的component组件,在connect最终返回的组件中获取store并将store设置为当前组件的state,并且在connect返回的组件中的componentDidMount周期函数中调用subscribe给store绑定监听函数,而这个监听函数就是负责当前store中的state发生改变时,通过this.setState来触发组件的render函数的调用,最终达到store中的state与UI中state同步的问题

react-redux有哪些API?

1.Provider组件通过context的方式将store注入应用
2.Connect高阶组件,获取并监听store,然后根据store state和组件自身props计算得到新props,注入该组件,并且可以通过监听store,比较计算出的新props判断是否需要更新组件

Provider的实现


import React, { Component } from 'react'
import PropTypes from 'prop-types'
 
class Provider extends Component {
 
    constructor (props) {
        super(props)
        this.store = props.store
    }
 
    static propTypes = {
        store: PropTypes.object
    }
 
    getChildContext () {
        return { store: this.store }
    }
 
    render () {
        return this.props.children
    }
}

若存在疑问请回顾上面react-redux的原理分析

connect的实现

import React, { Component } from 'react'
import PropTyeps from 'prop-types'
import { bindActionCreator } from 'redux'
 
const connect = (mapStateToProps, dispatchStateToProps) => (WrapperComponent) => class Connect extends Component {
    
    construtor (props, context) {
        super(props, context)
        this.store = context.store
        this.state = {
            props: {}
        }
    }
    
    static contextTypes = {
        store: PropTypes.object
    }
 
    componentDidMount () {
        this.store.subscribe(this.update)
        this.update()
    }
 
    update = () => {
        const { getState, dispatch } = this.store
        const stateProps = mapStateToProps(getState())
        const dispatchProps = bindActionCreator(dispatchStateToProps, dispatch)
        this.setState({
            ...this.state.props,
            ...stateProps,
            ...dispatchProps,
        })
    }
    
    render () {
        const { props } = this.state
        return <WrapperComponent {...props} />
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值