React Redux简朴完成

设想头脑

1.web运用是一个状况机,试图与状况是一一对应的.
2.一切的状况,保留在一个对象里.

基础转变和API

1.Store
Store就是保留数据的处所,你能够把它算作一个容器,全部运用只能有一个Store.
Redux供应createStore这个函数,用来天生Store.

import { createStore } from 'redux';
const store = createStore(reducer);
createStore函数接收另一个reducer函数作为参数,返回新天生的Store对象.

2.State
State对象包括一切数据,假如想获得某个时点的数据,就要对Store天生快照,这类时点的数据鸠合,
就叫做State.当前时刻的State,能够经由历程store.getState()拿到.

const state = store.getState();

3.Action
state的变化,会致使view的变化,然则,用户打仗不到state,只能打仗到view,所以.stated的变化必需是view致使的.Action就是view发出的关照,示意state应该要发作变化了.
Action是一个对象,个中的type属性是必需的,示意Action的称号,其他属性能够自在设置.

const action = {
    type: 'ADD_TODO',
    payload: 'learn Redux'
};

Action的称号是ADD_TODO,它照顾的信息是字符串Learn Redux.
能够如许明白,Action形貌当前发作的事变,转变State的唯一要领,就是运用Action,它会输送数据到Store.

4.Action Creator
View要发送若干种信息,就会有若干种Action,能够定义一个函数天生Action,这个函数就叫ActionCreator.

const ADD_TODO = '增加 TODO';
function addToDo(text) {
    return {
        type: ADD_TODO,
        text
    }
}

5.store.dispatch()
store.dispatch()是view发出Action的唯一要领.

store.dispatch(addTODO('Learn Redux'));

6.reducer
store收到Action今后,必需给出一个新的State,如许view才会发作变化.
这类State的盘算历程就叫做Reducer.
Reducer是一个函数,他接收Action和当前State作为参数,返回一个新的State.

export default (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        case 'getSource':
            return 'bbbb';
        default:
            return 0;
    }
}

reducer函数收到名为ADD的action今后,就返回一个新的state,作为加法的盘算结果,其他盘算的逻辑,
也能够依据Action的不同来完成.
现实运用中,Reducer函数不必像上面如许手动挪用,store.dispatch要领会触发Reducer的自动实行.
为此,Store须要晓得Reducer函数,做法就是天生Store的时刻,将Reducer传入createStore要领.

const store = createStore(reducer);

createStore接收Reducer作为参数,天生一个新的Store.今后每当store.dispatch发送过来一个新的Action,
就会自动挪用Reducer,获得新的State.
7.纯函数
Reducer函数最主要的特性是,它是一个纯函数,也就是说,只如果一样的输入,必需获得一样的输出.
因为Reducer是纯函数,就能够保证一样的State,一定获得一样的view,但正因为这一点,Reducer函数内里不能转变
State,必需返回一个全新的对象.

return Object.assign({}, state, { thingToChange })
export default (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        case 'getSource':
            return 'bbbb';
        case 'ajax':
            return action.data;
        case 'ajaxError':
            return action.data
        default:
            return 0;
    }
}

8.store.subscribe()
Store许可运用store.subscribe要领设置监听函数,一旦State发作变化,就自定实行这个函数.

store.subscribe(listener);

明显,只需把view的更新函数(render或this.setState)放入listen,就会完成view的自动衬着.
let unsubscribe= store.subscribe(() => console.log(store.getState()));
unsubscribe();

Store的完成

1.store.getState(),store.dispatch(),store.subscribe()

let { subscribe, dispatch, getState } = createStore(reducer);

Reducer的拆分

Reducer函数担任天生State,因为全部运用只需一个state对象,包括一切数据,关于大型运用来讲,这个State
必定非常巨大,致使Reducer函数也非常巨大.
Redux供应了一个combineReducers要领,用于Reducer的拆分,你只需定义各个子Render函数,
然后用这个要领,将它们合成一个大的Reducer.

import { combineReducers } from 'redux';

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})

事情流程

1.用户发出Action

store.dispatch(action);

2.Store自动挪用Reducer,而且传入两个参数,当前State和收到的Action.Reducer会返回新的State.

let nextState = todoApp(previousState, action);

3.State一旦有变化,Store就会挪用监听函数.

store.subscribe(listener);

4.listener能够经由历程store.getState()获得当前状况,假如运用的是React,这时候能够触发从新衬着view.

function listerner() {
  let newState = store.getState();
  component.setState(newState);   
}

实例

import React, { Component } from 'react';
import { render } from 'react-dom';
import reducer from '../reducers/reducer.js';
import { createStore } from 'redux';

const store = createStore(reducer);

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
            source: 'aaaa',
            ajaxSource: 'ajax'
        };
    }
    handleAdd = () => {
        store.dispatch({
            type: 'INCREMENT'
        });
    }
    handleDel = () => {
        store.dispatch({
            type: 'DECREMENT'
        });
    }
    handleGet = () => {
        store.dispatch({
            type: 'getSource'
        })
    }
    handleAjax = () => {
        fetch('../api/response.json')
        .then(response => response.json())
        .then((res) => {
            store.dispatch({
                type: 'ajax',
                data: res
            });
        }).catch((err) => {
            store.dispatch({
                type: 'ajaxError',
                data: err
            });
        })
    }
    render() {
        let _this = this;
        store.subscribe(() => {
            let o = store.getState();
            _this.setState({
                [o.type]: store.getState()[o.type]
            })
        });
        return (
            <div>
                <span>{ this.state.count }</span>
                <button onClick={ this.handleAdd }>add</button>
                <button onClick={ this.handleDel }>del</button>
                <span>{ this.state.source }</span>
                <button onClick={ this.handleGet }>猎取数据</button>
                <span>{ this.state.ajaxSource.res }</span>
                <button onClick={ this.handleAjax }>猎取ajax数据</button>
            </div>
        );
    }
}

render(<App />, document.getElementById('root'));
export default (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return Object.assign({}, state, {
                count: state + 1,
                type: 'count'
            });
        case 'DECREMENT':
            return Object.assign({}, state, {
                count: state - 1,
                type: 'count'
            });
        case 'getSource':
            return Object.assign({}, state, {
                source: action.dada,
                type: 'source'
            });
        case 'ajax':
            return Object.assign({}, state, {
                ajaxSource: action.data,
                type: 'ajaxSource'
            })
        case 'ajaxError':
            return Object.assign({}, state, {
                ajaxSource: action.data,
                type: 'ajaxSource'
            });
        default:
            return state
    }
}
    原文作者:蛋白
    原文地址: https://segmentfault.com/a/1190000010291841
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞