redux-thunk
# 一段关于使用redux-thunk 简单明了的代码
旁白(个人觉得这 redux-thunk 东西真没啥鸟用)
### 先来一段不使用redux-thunk
```javascript
import React, { Component } from 'react'
import { Provider, connect } from 'react-redux'
import { createStore } from 'redux'
// ---------------------------------------------
// 创建store
const num = (state = 1, e) => {
switch (e.type) {
case 'add':
return state + 1
case 'subtract':
return state - 1
default:
return state
}
}
const store = createStore(num)
console.log(store)
// ---------------------------------------------
// 定义和使用组件
class All extends Component {
render () {
return <Provider store={store}>
<But />
<Show />
</Provider>
}
}
class But123 extends Component { // But这是上面的按钮
render () {
return <div>
<button onClick={this.props.add}>add</button>
<button onClick={this.props.subtract}>subtract</button>
</div>
}
}
const mapStateToProps = state => ({
num: state
})
const mapDispatchToProps = dispatch => ({
add: () => dispatch({type: 'add'}),
subtract: () => dispatch({type: 'subtract'})
})
const But = connect(mapStateToProps, mapDispatchToProps)(But123)
class Show123 extends Component {
render () {
// console.log(this.props)
return <div>
{this.props.num}
</div>
}
}
// Show这是下面显示的数字,利用connect实现实时获取store中的数据
const Show = connect(mapStateToProps)(Show123)
// ---------------------------------------------
export default All
```
不使用redux-thunk,把同步变异步
```javascript
把const mapDispatchToProps = dispatch => ({
add: () => dispatch({type: 'add'}),
subtract: () => dispatch({type: 'subtract'})
})中的add变成下面的
const mapDispatchToProps = dispatch => ({
add: () => setTimeout(() => dispatch({type: 'add'}), 2000),
subtract: () => dispatch({type: 'subtract'})
})
```
如果使用redux-thunk的话需要改一下
```javascript
// 把import { createStore } from 'redux' 改为下面的
import { createStore, applyMiddleware } from 'redux'
// 新增引入thunk
import thunk from 'redux-thunk'
// 把const store = createStore(num) 改为下面的
const store = createStore(num, applyMiddleware(thunk))
```
使用redux-thunk的话,还要改一些,下面这些就是重点了
(就是用中间件(或者称为高阶组件)把东西一层又一层的封装,把你绕晕掉,然后,哇,你就觉得这个东西好屌啊,好牛逼)
```javascript
// 把const mapDispatchToProps = dispatch => ({
add: () => dispatch({type: 'add'}),
subtract: () => dispatch({type: 'subtract'})
})改为下面的
const mapDispatchToProps = (dispatch) => ({
// value是调取add传的参数,getState可以获取数据
add: value => dispatch((dispatch, getState) => {
console.log(value)
console.log(getState())
setTimeout(() => dispatch({type: 'add'}), 3000)
}),
subtract: () => dispatch({type: 'subtract'})
})
//value传参可以这样传
把class But123 extends Component { // But这是上面的按钮
render () {
return <div>
<button onClick={this.props.add}>add</button>
<button onClick={this.props.subtract}>subtract</button>
</div>
}
}改为下面的
class But123 extends Component { // But这是上面的按钮
render () {
return <div>
// 加了.bind(null, 123),这样写在性能优化上不好,为了方便理解,就这样写了
<button onClick={this.props.add.bind(null, 123)}>add</button>
<button onClick={this.props.subtract}>subtract</button>
</div>
}
}
```
就是上面这段代码是重点,为啥说是重点,简单明了的可以发现redux-thunk 这东西没啥鸟用,
就是封装,多包几层,绕死你