Redux官網Counter最基本示例的思考

1.不使用redux實現

如果不使用redux,僅僅依靠react去實現Counter功能是極其簡單的。代碼如下:
在這裏插入圖片描述
index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './components/Counter';

const render = ()=> ReactDOM.render(
    <Counter/>,
    document.getElementById("root")
);

render();

components/Counter.js

import React, {Component} from 'react';

class Counter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0
        };
        this.add = this.add.bind(this);
        this.addOdd = this.addOdd.bind(this);
        this.addAsync = this.addAsync.bind(this);
        this.minus = this.minus.bind(this);
    }

    add() {
        this.setState({
            counter: ++this.state.counter
        })
    }

    addOdd() {
        let counter = this.state.counter;
        if (counter % 2 === 1) {
            this.setState({
                counter: ++counter
            })
        }
    }

    addAsync() {
        setTimeout(this.add, 1000);
    }

    minus() {
        this.setState({
            counter: --this.state.counter
        })
    }

    render() {
        return (
            <div>
                Clicked:{this.state.counter} times
                {' '}
                <button onClick={this.add}>+</button>
                {' '}
                <button onClick={this.minus}>-</button>
                {' '}
                <button onClick={this.addOdd}>Increment if odd</button>
                {' '}
                <button onClick={this.addAsync}>Increment async</button>
            </div>
        )
    }
}

export default Counter;

僅僅兩個文件就可以實現,Counter功能。那爲啥非要引入Redux呢?從自己僅有的這點react經驗來看:1.本例中的狀態只有counter一個,如果應用足夠複雜,在組件內部自己管理狀態,而這些狀態又會影響其他子組件。爲管理這個狀態而編寫的代碼量將會難以閱讀和維護,添加新功能也會很麻煩。2.通過用戶事件去改變狀態,本身沒錯,但是這些狀態沒有統一的操作去統一的state數據結構。redux就是想讓狀態統一管理,統一執行action操作,讓 state 的變化變得可預測

2.使用redux

下面是加入redux之後的項目代碼:在這裏插入圖片描述
多了一個reducers/index.js文件。

export default (state =0,action) =>{
    switch (action.type){
        case "INCREASE":
            return state+1;
        case "DECREASE":
            return state-1;
        default:
            return state;
    }
}

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './components/Counter';
import {createStore} from 'redux';
import counter from './reducers';

const store = createStore(counter);

const render = ()=> ReactDOM.render(
    /*返回應用當前的 state 樹,它與 store 的最後一個 reducer 返回值相同。*/
    <Counter counter={store.getState()}
        add={()=>store.dispatch({type:'INCREASE'})}
        minus={()=>store.dispatch({type:'DECREASE'})}
    />,
    document.getElementById("root")
);

render();
store.subscribe(render);

components/Counter.js

import React, {Component} from 'react';
import PropTypes from 'prop-types';


class Counter extends Component {
    constructor(props) {
        super(props);
        this.addOdd = this.addOdd.bind(this);
        this.addAsync = this.addAsync.bind(this);
    }


    addOdd() {
        let counter = this.props.counter;
        if (counter % 2 === 1) {
            this.props.add()
        }
    }

    addAsync() {
        setTimeout(this.props.add, 1000);
    }



    render() {
        const { counter, add, minus } = this.props;
        return (
            <div>
                Clicked:{counter} times
                {' '}
                <button onClick={add}>+</button>
                {' '}
                <button onClick={minus}>-</button>
                {' '}
                <button onClick={this.addOdd}>Increment if ODD</button>
                {' '}
                <button onClick={this.addAsync}>Increment async</button>
            </div>
        )
    }
}
//嚴格定義參數類型
Counter.propTypes = {
    counter: PropTypes.number.isRequired,
    add: PropTypes.func.isRequired,
    minus: PropTypes.func.isRequired
};

export default Counter;

在使用redux之後,Counter,中的狀態管理被統一到store中,通過store.dispatch(action)的方法唯一的去修改state內容,具體的:會使用當前 getState() 的結果和傳入的 action 以同步方式的調用 store 的 reduce 函數。返回值會被作爲下一個 state。從現在開始,這就成爲了 getState() 的返回值,同時變化監聽器(change listener)會被觸發。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章