简体   繁体   English

如何基于AJAX调用设置Redux Reducer的初始状态?

[英]How to set Redux Reducer's initial state based on AJAX call?

Using Redux, I want one of my reducers initial state to be based on an AJAX call. 使用Redux,我希望我的reducer的初始状态之一基于AJAX调用。 Basically, I am using AJAX to get some data, and then putting it into the state of the Reducer. 基本上,我使用AJAX来获取一些数据,然后将其置于Reducer的状态。 However, because of the AJAX call, the reducer is initialized with the initial state before the AJAX call is complete. 但是,由于进行了AJAX调用,在完成AJAX调用之前,将reducer初始化为初始状态。 How would you go about making reducer wait until the AJAX call is complete before setting the initial state? 在设置初始状态之前,如何使reducer等待AJAX​​调用完成?

STORE 商店

export default () => {
  const store = createStore(
    combineReducers({
      settings: settingsReducer,
    })
  );
  return store;
}

REDUCER 减速器

var settingsDefaultState;

$.ajax({
  url: 'view/content/settings.xml',
  type: 'GET',
  success: function(xml) {
    //DOING SOME STUFF WITH THE XML FILE HERE
    settingsDefaultState = {
      test: "HELLO WORLD"
    }
  },
  complete: function() {
    console.log("Settings Loaded...");
  }
});


export default (state, action) => {
  var tempState = {...state};
  switch (action.type) {
    default:
      return tempState;
  }
}

I suggest you initialize your state as a loading state. 我建议您将状态初始化为loading状态。 That way you can give feedback to the user that something is happening. 这样,您可以将发生的事情反馈给用户。 Then when the ajax call returns a response you trigger an action that will set your state to the desired next state. 然后,当ajax调用返回响应时,您将触发将状态设置为所需的下一个状态的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM