Understanding redux thought (a)

First, create a, store this is a must

import { createStore } from 'redux';

import reducer  from './reducer'

const store = createStore(reducer);

reducer is a function, we define some rules, and these rules can change a function of the state, and vuex of mutations is a reason that it takes two arguments, the first argument is the state, the second parameter is actions, we pass some of the data that is required for participation

code as follows reducer

const reducer = (state = 0, action) => {
    switch (action.type) {
        case 'ADD':
            return state + action.value;
        default:
            return state;
    }
};

export default reducer

So we got the state, printed in the console about the state, get:

Next, talk about dispatch, getState, subscribe

First, store.getState acquisition is a function of the state, have performed this function retrieves the current state, a series of values

   Implementation of this function, the equivalent of the state vuex

let state = store.getState();

Second, store.dispatch this function is the only change worthy of a state function

  This function is equivalent to the actions vuex 

// 改变
store.dispatch({
    type: 'ADD',
    value: '2'
})

console.log(state)   // 0

After this step, the printed results found, is still 0, so we need to manually re-execute this function a getState

store.dispatch({
    type: 'ADD',
    value: '2'
})
console.log(state)   // 0
state = store.getState();

console.log(state)  // 2

 

Although this state can get what we want, but every time we have to change state when getState should call this function, it is too much trouble

So we introduced subscribe

Third, store.subscribe this function is a value store, as long as a change occurs, this function is performed automatically, i.e., update the view

const Counter = ({ value }) => (
    <h1>{value}</h1>
);

const render = () => {
    ReactDOM.render(
        <Counter value={store.getState()}/>,
        document.getElementById('root')
    );
};

store.subscribe(render);
render();

Summary: Although this view can be updated, but react, the transfer route between the props, you can dynamically create the component, and then give the component settings props and other ideas to achieve, but the feeling is not always convenient, so when in use react birth react-redux appears for granted

Guess you like

Origin blog.csdn.net/luchuanqi67/article/details/80888333