我有一个reactJs应用程序,现在我正在学习Redux以将其用作Flux实现。Redux:只有同步调用允许从reducer功能?
我创建了一个商店,我已经创建了我的第一个减速功能,但现在我有一些问题,来我的心,请帮我明白了。
正如你可以看到我有一个名为“FIND_PRODUCTS”这基本上是从后端服务中获取数据的作用。为了调用这个后端服务,我基本上使用了一个异步的ajax调用,所以基本上我面临的问题是,在我的后端调用完成之前,状态是从reducer函数返回的,因此状态没有正确更新,并且用户该商店正在获取不正确的数据。如果我切换到同步调用,这个问题就解决了,但是,我得到的第一个警告是应该避免同步调用,因为它可能会降低用户的体验(性能)。
所以我的问题,可我们只从同步减速功能获取数据? 提取数据是否应该在reducer函数中发生,或者有另一种方法可以做到这一点?如果是这样,那是什么?
是否具有单一的对象树与大型应用程序维护国家尺度很好的终极版这种模式?如果我有1000个动作,那么我的减速器功能中的开关就会很大!我们如何避免这种情况?
谢谢!
const initialState = {
availableLocales: [{text: 'En'}, {text: 'Es'}, {text: 'Fr'}],
selectedLocale: 'En',
translations: i18n.getTranslations(),
products: []
};
const reducer = (state = initialState, action = {type: 'NONE'})=> {
//To make the reducer a pure function
deepFreeze(state);
deepFreeze(action);
switch (action.type) {
case 'SWITCH_LOCALE':
let newState = Object.assign({}, state, {
selectedLocale: action.locale,
translations: i18n.getTranslations(action.locale)
});
return newState;
case 'FIND_PRODUCTS':
let newState = Object.assign({}, state, {
products:ProductHelper().findProductsByProductType(action.productType)
});
return newState;
default:
return state
}
return state;
}
// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
const store = createStore(reducer);
// You can subscribe to the updates manually, or use bindings to your view layer.
store.subscribe(() =>
console.log(store.getState())
);
export default store;
组件不能调用componentWillMount方法的findProduct异步函数吗? – Raulucco
当然,但是我们需要什么店?我认为这一切的关键是将国家从零部件转移到商店.. – fgonzalez