天天看點

使用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操作狀态)

繼續閱讀