API中的Redux存储的defaultState

时间:2016-05-28 14:54:24

标签: reactjs redux react-redux

如何使我的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);

1 个答案:

答案 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')
  );
});