天天看點

React-Redux-綜合運用(在React中使用)

在之前的 ​​React-Redux-優化​​ 文章當中說明了一個問題需要解決,在本文主要介紹的就是這個問題的解決方案;

  • store、action、reducer 代碼都寫在一個檔案中,不利于維護

這個問題呢,可以在項目工程當中建立一個 store 檔案夾,在該檔案夾當中分别建立 ​

​action.js​

​​,​

​constants.js​

​​,​

​reducer.js​

​​,​

​store.js​

​ 等檔案:

  • action.js
import {
    ADD_COUNT,
    SUB_COUNT
} from './constants';

// 利用action來修改狀态
export const addAction = (num) => {
    return {type: ADD_COUNT, num: num};
};
export const subAction = (num) => {
    return {type: SUB_COUNT, num: num};
};      
  • constants.js
export const ADD_COUNT = 'ADD_COUNT';
export const SUB_COUNT = 'SUB_COUNT';      
  • reducer.js
import {
    ADD_COUNT,
    SUB_COUNT
} from './constants';

// 定義一個狀态
let initialState = {
    count: 666
};

// 利用reducer将store和action串聯起來
function reducer(state = initialState, action) {
    switch (action.type) {
        case ADD_COUNT:
            return {count: state.count + action.num};
        case SUB_COUNT:
            return {count: state.count - action.num};
        default:
            return state;
    }
}

export default reducer;      
  • store.js
import {createStore} from 'redux';
import reducer from './reducer';

// 利用store來儲存狀态(state)
const store = createStore(reducer);

export default store;      

使用 Redux

  • App.js
import React from 'react';
import store from './store/store';
import {addAction, subAction} from './store/action';

class App extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            count: store.getState().count
        }
    }

    componentDidMount() {
        store.subscribe(() => {
            this.setState({
                count: store.getState().count
            })
        })
    }

    componentWillUnmount() {
        store.unsubscribe();
    }

    render() {
        return (
            <div>
                <p>{this.state.count}</p>
                <button onClick={() => {
                    this.btnClick()
                }}>
                    增加
                </button>
            </div>
        )
    }

    btnClick() {
        store.dispatch(addAction(5));
    }
}

export default App;      

繼續閱讀