Redux realization of createStore

Redux realization of createStore

  Used react students should understand this thing Redux. He is a global state management thinking (right, here I think it is an idea, because for React, in fact, inside Redux and nothing needs to be compatible with React things, react-redux library only), it It believes in:

  • The only data warehouse
  • Only read
  • Data can only be changed by a pure function

  In fact, this is a constraint for us, after all, even if we introduced Redux, also can be used this.propsto carry out the assembly of parent-child data transmission, but when you need a non-parent-child communication components, which the data flow will be very elusive, so we use Redux.

In React when integrated Redux, at the entrance to the program, we can see this piece of code

// 这里的todoApp是一个Reducer函数,接受的是state和actions
const store = createStore(todoApp)

  When we react in a single warehouse to see what some of the similar code, from which we can see, we have this component stateis through this.state = store.getState()the creation, then we storeare a target, which has a getStatefunction to return internal the statesame time this stateis the need to persist, so we can probably have some ideas.

import React, { Component } from 'react'
import store from '../../store'
import { getIPData } from '../../store/actionCreators'

class Page extends Component {
    // 我的初始化的一个组件,已经能够使用Redux了
    constructor(props) {
        super(props);
        this.state = store.getState()
        store.subscribe(this.storeChange.bind(this));
    }

    componentWillMount() {
        // 获取IP数据,这里是作为一个dispatch的例子
        // 值得注意的是getIPData()返回的是一个带type字段的一个对象。
        const action = getIPData();
        store.dispatch(action);
    }

    render() {
        return (
            <div className="page">
            </div>
        )
    }

    storeChange() {
        this.setState(store.getState())
    }
}
export default Page

  Next, I will write their own createStorefunctions stick out, and then explain. This function implements most of the functionality, but to deal with middleware here and never came to fruition, I should be back because they have few additions.


export default function createStore(reducer){
    let state = null;
    const listeners = [];
    const getState = () => state
    
    const dispatch = (action) => {
        state = reducer(state, action)
        listeners.forEach(listener => listener())
    }
    
    const subscribe = (listener) => listeners.push(listener)
    
    // 这里初始化dispatch的原因是在这之前,state是为null的
    //所以我需要传一个不存在的action去reducer里面,拿到最默认的那个defaultState
    //这个defaultState写在reducer的那个文件里面
    dispatch({});
    return {
        dispatch,
        subscribe,
        getState,
    }
}

  So just analysis, we need to create a function objectcreateStore

  1, createStorewhich method closure of a store state, a warehouse used by our program is this, there is also a function of the storage array listenersfor storing user-defined functions (generally used warehouse reset after the update this.state), because I actually there are multiple pages registered a subscription function, so use an array of functions when you need to take out the distribution can be taken out call.

  2, createStoreneed to define a method getStatecan get state, so it can be used in React this.state = store.getState()to initialize stateand read

  3, createStorealso need to define a method dispatch, because redux can not directly modify statethe value, must dispatchfunction, passing action, and then with statedirect incoming reduceryears, reducerthe returns modified state.

  4, createStorethen you need to define a method subscribe, this function is used to monitor changes in the use of binding a function that would get in the outside world state. So this function should receive a function, then push into a queue, but should monitor in real time, why do you want to place the queue? Here is my understanding, it will be "outside regain state" at the beginning of this function into the queue similar promise I promise to use this function. Therefore, use of this function should be placed dispatchinside, it returns a statepost, do is to "regain the outside world state" in all queues functions all out to perform again.

  So the createStoreeffect is very obvious function, getStateto get the current state, subscribeis used to set the monitor and external monitor function is stored in the createStoreproperties of the function, each user through dispatchpass actionto modify the statetime, all of which will monitor the implementation of functions out again. And dispatchit is used to perform the statemodification, after all, this function does not allow setStatethis type of function.

  In this way, we simply understand and analyze the basic principles of Redux and its rewritten, as I mentioned, Redux is a kind of ideological constraints arise, which means that node, we can also use Redux (although I think it may not be necessary)

Guess you like

Origin www.cnblogs.com/JobsOfferings/p/Redux_createStore.html