我已经成功编写了一些将通过redux流程的代码,点击一个按钮后,它将在UI上显示我想要的信息。
我正在使用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
我应该怎么做?谢谢!
答案 0 :(得分:0)
这个问题听起来好像你还没有真正安装了redux-thunk中间件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
像这样设置你的商店之后,你的例子应该可行。