如何使我的Redux存储库的默认状态成为来自API请求的数据?
我想发出这样的请求,然后在创建商店时将返回的数据作为defaultState
传递:
const request = new XMLHttpRequest();
request.open('GET', '/api', true);
request.onload = function load() {
if (this.status >= 200 && this.status < 400) {
const data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
const store = createStore(rootReducer, defaultState, enhancers);
答案 0 :(得分:1)
如果您想将异步加载状态设置为默认状态,则应在index.js
中启动应用程序之前尝试加载它:
import reducer from './reducer';
function asyncStateLoadingFunction(callback) {
const request = new XMLHttpRequest();
request.open('GET', '/api', true);
request.onload = function load() {
if (this.status >= 200 && this.status < 400) {
callback(JSON.parse(this.response));
} else {
callback(null, 'Error occured');
}
};
};
Promise((resolve, reject) => {
asyncStateLoadingFunction((result) => {
resolve(result);
}, (error) => {
throw new Error(error);
});
})
.then((initialState) => {
// NOTE Create the Redux store, routers etc now
const store = createStore(reducer, initialState);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querySelector('#app')
);
});