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


react-redux、redux

connect、Provider,createStore

  • 用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    "babel": {
    "presets": [
    "react-app"
    ],
    "plugins": [
    "transform-decorators-legacy"
    ]
    }

    ``````bash
    npm install --save babel-plugin-transform-decorators-legacy

1
2
3
// 直接替换上面的connect方法
@connect((state)=> {return {num: state}}, {add, sub})

reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 // 配置调试
));