2016-10-02 71 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) 
); 

设置你的店一样,之后,你的榜样应该工作。