【发布时间】:2016-04-14 06:26:53
【问题描述】:
我正在使用 React 和 Redux 构建一个工具。我正在使用 whatwg-fetch 进行服务器端调用并获取一些数据。而且我有一个reducer,在成功获取数据后,它将在回调中创建其存储。这是我的代码:
import {createStore} from 'redux';
import 'whatwg-fetch';
let notificationCardList = [],
initialState,
store;
const fetchData = () => {
fetch('http://localhost:6767/file/data.json')
.then((response) => response.json())
.then((responseData) => {
notificationCardList = Object.keys(responseData).map(key => responseData[key]);
})
.then(initializeReducer);
}
const initializeReducer = () => {
initialState = {
notifCardsToBeDisplayed: notificationCardList,
notifCardToBeDisplayed: null
};
function manipulateNotificationCards (state = initialState, action) {
switch (action.type) {
case 'OPEN_CARD':
return Object.assign(state, {
notifCardsToBeDisplayed: null,
notifCardToBeDisplayed: action.card,
notifCardsContainerPreviousState: action.notifCardsContainerCurrentState
});
case 'DISPLAY_CARD_LIST':
return Object.assign(state, {
notifCardsToBeDisplayed: action.cards,
notifCardToBeDisplayed: null
});
default:
return state;
}
}
store = createStore(manipulateNotificationCards);
}
fetchData();
export {store, notificationCardList};
但是由于存储是作为回调的一部分创建的,由于异步行为,导出语句可能在 createStore() 语句之前执行,因此我有效地导出了一个未定义的“存储”。我也想过将 export 语句放在回调中,但话又说回来,export 语句只能放在顶层。我也尝试过使用 setTimeout(),但这也没有用。有什么方法可以在创建后导出“商店”?
【问题讨论】:
标签: javascript reactjs ecmascript-6 redux react-redux