React、Redux和redux-thunk的简单应用

 后端   大苹果   2018-05-22 09:32   1685

react-redux、redux

connect、Provider,createStore

  • 用法
// redux/index.js
const ADD = 'add';
const SUB = 'sub';
export function counter(state = 0, action) {
    switch(action.type) {
        case ADD:
            return state + 1;
        case SUB:
            return state - 1;
        default:
            return state;
    }
}

// action
export function add() {
    return {type: ADD};
}
// action
export function sub() {
    return {type: SUB};
}
// index.js 入口
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import {counter} from './redux/index';
import {createStore} from 'redux';
import {Provider} from 'react-redux';

let store = createStore(counter);
// 通过props传递store
ReactDOM.render(
    <Provider store={store}>
        <div>
            <App />
        </div>
    </Provider>
    , 
    document.getElementById('root')
);

// App.js
import react from 'react'
import {connect} from 'react-redux'
import {add, sub} from './reduxs/index'
class App extends react.Component {
    render() {
        return (
            <div>
                <span>{this.props.num}</span>
                <button onClick={this.props.add}>add</button>
                <button onClick={this.props.sub}>sub</button>
            </div>
        );
    }
}
const MapStateToProps = (state) => {
    return {num};
}
const ActionCreator = {add, sub};
App = connect(MapStateToProps, ActionCreator)(App);

装饰器

配置

  • 配置babel

    package.json里面找到babel,增加插件transform-decorators-legacy

    "babel": {
        "presets": [
        "react-app"
        ],
        "plugins": [
            "transform-decorators-legacy"
        ]
    }
    
    npm install --save babel-plugin-transform-decorators-legacy
    
// 直接替换上面的connect方法
@connect((state)=> {return {num: state}}, {add, sub})

reducer

import {combineReducers} from 'redux'
import {counter} from './redux/index'
const todoApp = combineReducers({
    counter
})
export default todoApp
// index.js
import reducers from './reducer'
// 解决异步等待
import thunk from 'redux-thunk'
import {createStore, applyMiddleware, compose} from 'redux';
// 开启redux调试功能
const reduxDevTools = window.devToolsExtension ? window.devToolsExtension() : ()=>{};
const store = createStore(reducers, compose(
    applyMiddleware(thunk), // 使用中间件thunk
    reduxDevTools // 配置调试
));