2016-10-02 72 views
0

我已經成功編寫了一些代碼,它將通過redux流程,點擊一個按鈕後,它會在UI上顯示我想要的信息。我正在使用este stack如何使用React/Redux(este stack)執行異步操作

這是我的按鈕:

const Buttons = ({ requestAsyncData}) => (
    <View> 
    <Button onClick={requestAsyncData}> 
     <FormattedMessage {...buttonsMessages.add100} /> 
    </Button> 
    </View> 
); 

export default connect(state => ({}), { requestAsyncData })(Buttons); 

現在,這裏是我定義的操作:

export const REQUEST_ASYNC_DATA = 'REQUEST_ASYNC_DATA'; 

export const requestAsyncData =() => { 

    return { 
    type: REQUEST_ASYNC_DATA, 
    payload: [{ 
     name: "one one!", 
     id: Math.random() 
    },{ 
     name: "two two!", 
     id: Math.random() 
    }] 
    } 

這裏是我的減速器:

const State = Record({ 
    map: Map() 
}, "names"); 

const asyncExampleReducer = (state = new State(), action) => { 
    switch (action.type) { 

    case actions.REQUEST_ASYNC_DATA: { 
     const names = action.payload.reduce((names, json) => 
      names.set(json.id, new Name(json)) 
     , Map()); 
     return state.update('map', map => map.merge(names)); 
    } 

    default: 
     return state; 

    } 
}; 

export default asyncExampleReducer; 

這工作完全按照預期ui,更新正確的信息,從行動中,我得到實際的有效載荷來做我喜歡的:

payload: [{ 
    name: "one one!", 
    id: Math.random() 
},{ 
    name: "two two!", 
    id: Math.random() 
}] 

現在,我試圖讓這個有效載荷異步的,比方說我會從Ajax API調用獲取該對象的信息。

我應該怎麼辦?

我不知道如果我需要去thunks或者我應該做一些建議here,我一直在嘗試各種建議,但我不確定如果我的問題是JavaScript的具體問題或理解反應。

比如我試圖做一個類似的建議的thunk的行動,但不承認調度,它似乎並沒有任何延遲它...

function doIncrementAction() { 
    return { 
    type: REQUEST_ASYNC_DATA, 
    payload: [{ 
     name: "trufa!", 
     id: Math.random() 
    },{ 
     name: "benja!", 
     id: Math.random() 
    }] 
    } 
} 

export const requestAsyncData =() => { 
    return dispatch => { 
     setTimeout(() => { 
     // Yay! Can invoke sync or async actions with `dispatch` 
     dispatch(doIncrementAction()); 
     }, 1000); 
    }; 
}; 

raven.js:290 Uncaught TypeError: Cannot read property 'payload' of undefined 

raven.js:290 Uncaught TypeError: dispatch is not a function 

我應該怎麼做?謝謝!!

+1

你有沒有看過[Sagas](https://github.com/yelouafi/redux-saga/)?它們是將API調用(和其他異步操作)綁定到Redux數據流的一種方式。 – christopher

+0

@christopher我沒有,但我會現在。謝謝 – Trufa

+0

他們使用一些ES6的概念,所以你需要一個轉譯器,但我發現他們是一個非常乾淨的方法來做一個Redux框架內的異步操作。 – christopher

回答

0

問題聽起來好像你還沒有真正安裝了Redux-形實轉換中間件:

import { createStore, applyMiddleware } from 'redux'; 
import thunk from 'redux-thunk'; 
import rootReducer from './reducers/index'; 

// Note: this API requires [email protected]>=3.1.0 
const store = createStore(
    rootReducer, 
    applyMiddleware(thunk) 
); 

設置你的店一樣,之後,你的榜樣應該工作。