React 教程第十一篇 —— Redux 簡介和簡單實現

Redux

前端框架的組件式開發永遠有一道鴻溝——跨組件通訊。我在 Vue 教程中有提到過,若是對跨組件通訊不明白的可先跳過去看看。javascript

React 不一樣與雙向數據綁定框架,它是單向數據流,因此每次更新都得調用setState,因此在跨組件通訊中會比較迂迴。還有就是 React 沒有邏輯分層,在開發過程當中,邏輯分層是很重要的。前端

Redux 實現了跨組件通訊和邏輯分層的好處,因此在 React 中使用 Redux 更配。java

Redux 簡單實現

爲了說明問題,先來一個公共對象實現跨組件通訊。固然這個也是 flux 的實現原理。react

actions.js
export default {
    increment(){
        return {
            type: "+"
        }
    },
    decrement(){
        return {
            type: '-'
        }
    }
}
reducer
export default (state = 0, action) => {
    switch(action.type){
        case '+':
            return state + 1;
        case '-':
            return state - 1;
        default:
            return state;
    }
}

component

import React, {Component} from 'react'
import {createStore} from 'redux'
import Actions from './actions'
import Reducer from './reducer'

const store = createStore(Reducer);

export default class Component1 extends Component{
    constructor(props){
        super(props);
        this.state = {count: 0}
    }
    increment = () => {
        store.dispatch(Actions.increment());
        this.setState({
            count: store.getState()
        })
    }
    
    render(){
        return (
            <div>
                <h3>component-cp1-{this.state.count}</h3>
                <input type="button" value="increment" onClick={this.increment}/>
            </div>
        )
    }
}

小結——分層

  • Actions 層redux

    • 用戶行爲操做,由用戶在 View 層觸發 store.dispatch(Actions.increment());
    • 行爲操做應該爲一個 function且必須返回有type屬性的對象
    • 每一個方法都應該由store進行派發。
  • Reducer 層segmentfault

    • 必須是一個純函數(一個函數的返回結果只依賴於它的參數,而且在執行過程裏面沒有反作用)
    • 接受兩個參數,第一個爲state,另外一個爲action
    • return的結果能夠用store.getState()來接收
  • Store 層前端框架

    • redux的一個方法,接受reducer,返回一個對象store
    • 對象store的方法dispath用於派發action
    • 經過dispath派發的action會觸發reducer
  • View 層框架

    • 視圖層,也就是組件
    • 經過getState()獲取的值而後再setState即可以顯示。
相關文章
相關標籤/搜索