本文主要是介绍使用redux-thunk实现异步redux(基础文章),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用redux-thunk实现异步redux
Redux存在一个问题,就是无法实现异步的action,这也就是为什么我们要引入redux-thunk的原因。
在哪里引入redux-thunk?
在redux的核心组件store中引入。我们引入的这个thunk,相当于一个中间件。所以我们同时需要从redux中引入applyMiddleware,放入createStore的第二个参数中。
import {createStore,applyMiddleware} from 'redux';
import reducer from './reducer'
import thunk from 'redux-thunk'export default createStore(reducer,applyMiddleware(thunk))
异步action和普通的action有什么不同?
普通action返回的是对象,但是异步action返回的是一个函数。
异步action和同步action的区别
// 同步action
export const decrement = (number) => ({type: DECREMENT,data: number});
// 异步增加的action
export const incrementAsync = (number) => {return dispatch => {setTimeout(() => {dispatch({type: INCREMENT,data: number})},1000)}
}
最后别忘了,组件中已经没有定时器了,定时器在异步action中。
incrementIfAsync = () => {const number = this.numberRef.current.value * 1;this.props.incrementAsync(number);
}
codeSandBox在线演示(使用redux-thunk实现异步action操作状态)
这篇关于使用redux-thunk实现异步redux(基础文章)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!