redux-thunk
实现一个异步的加数器
框架为: react
+ react-redux
+ redux-thunk
项目结构
代码如下
新建一个 component -> App.js
, 代码如下
// App.js
import '@babel/polyfill'
import * as React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import Index from './Index'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
const enhancer = applyMiddleware(thunk);
const configureStore = createStore(
rootReducer,
enhancer
);
function Main() {
return <Provider store={configureStore}>
<Index />
</Provider>
}
export default Main
Services
新建 services -> index.js
, 接口层
export function getData(){
return Promise.resolve({num:1})
}
Actions
新建 actions -> index.js
export const ADD_COUNT = 'ADD_COUNT'
export const ADD_COUNT_ASYNC = 'ADD_COUNT_ASYNC'
export const DECREASE_COUNT = 'DECREASE_COUNT'
import {getData} from '../services/index'
export function add_count(num) {
return {
type: ADD_COUNT,
num,
}
}
export const add_count_sync = () => (dispatch) => {
setTimeout(() => {
getData().then(res => {
console.log(res)
const { num } = res;
dispatch(add_count(num));
})
}, 1000);
}
Reducers
新建 reducers -> index.js
// index.js
import { combineReducers } from 'redux';
function count_change(state = 0, action = {}) {
console.log(action)
switch (action.type) {
case 'ADD_COUNT':
state = state + action.num
break;
default:
break;
}
return state
}
export default combineReducers({
count_change
})
Components
新建一个 components -> Index.js
import React from 'react'
import {connect} from 'react-redux'
import {add_count , add_count_sync} from '../actions/index'
import {getData} from '../services/index'
function Index(props) {
return <div>
当前数据 {props.state} <br></br>
<button onClick={()=>{
props.add_count_sync()
}}>点击我</button>
</div>
}
const mapStateToProps = function(store) {
return {
state: store.count_change
}
}
export default connect(mapStateToProps,{add_count_sync})(Index)
Redux-thunk 优缺点总结
优点
- 代码简洁明了
- 库代码量小
缺点
- 由于先调用的是接口层,导致代码可能会特别臃肿 , 设想一个例子
如果一个接口既需要触发 action 的 `A1` ,而且还需要触发 `A2`,
这样子可能会使得接口在异步的时候需要判断需要触发哪个 action , 会使得代码难以维护
补充
最新看了下大佬一些 blog, 顺便看了下 react-thunk
源码 , 只有非常简单的几句话,就是一个 柯理化函数
// node_modules\redux-thunk\es\index.js
/** A function that accepts a potential "extra argument" value to be injected later,
* and returns an instance of the thunk middleware that uses that value
*/
function createThunkMiddleware(extraArgument) {
// Standard Redux middleware definition pattern:
// See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
var middleware = function middleware(_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
// action 其实就是我们的 动态 antion
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument);
} // Otherwise, pass the action down the middleware chain as usual
return next(action);
};
};
};
return middleware;
}
var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
思考
这里有个 问题
, 其实上诉的 方法
不用 react-thunk
, 也能实现 , 完全不用去实现 asyncAction
,而且 action
也是 pure
const mapDispatchToProps = (dispatch) => {
return {
getMenuTreeFn: () => {
setTimeout(() => {
getData().then(res => {
console.log(res)
const { num } = res;
dispatch(add_count(num));
})
}, 5000);
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Index)
然后我找到这么一篇文章,
Why do we need middleware for async flow in Redux?
里面有个大佬的原话大概是:
- 为了更加贯彻
redux
的思想 - 而且
react-thunk
可以更好地调用getState
然后还修正了 action
必须是 pure
这段话,原话大概是:
I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past.
This is incorrect. The docs said this, but the docs were wrong.
Action creators were never required to be pure functions.
We fixed the docs to reflect that.
如果理解有错,欢迎大佬斧正