简体   繁体   English

如何获取异步redux initialState?

[英]how to get async redux initialState?

I need to get some of my initialState from server, before react-redux app mounted. 在安装react-redux应用之前,我需要从服务器获取一些initialState。

Right now I'm using this code: 现在,我正在使用以下代码:

//store.js (pseudocode)
const initialState = {
  userDate: {
    loggedIn:false,
    name: ""
  }
};

(async () => {
  const { data } = await axios.get("user/profile", { withCredentials: true });
  if (data.name) {
    initialState.userData = {
      ...initialState.userData,
      loggedIn: true,
      name: data.name
    };
  };

  const store = createStore(
    reducer,
    initialState
  );

  ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root")
  );
})();

But I think it is not "redux-style", and also, I wanna manage my initalState in reducers, not in root file, something like this: 但我认为它不是“ redux样式”,而且,我想在减速器中而不是在根文件中管理initalState,如下所示:

//userReduce.js (pseudocode)
const initialState = {
    loggedIn: false,
    name: ""
  };

const { data } = await axios.get("user/profile", { withCredentials: true });
if (data.name) {
  initialState = {
    loggedIn: true,
    name: data.name
  };
}

export default function userData(state = initialState, action) {
...
}

I know that I can make async actions to get data, but problem is while action dispatching, app already mounted, and redirect user as if he was not logged in. 我知道我可以执行异步操作来获取数据,但是问题是在操作分派,应用程序已挂载并重定向用户时(好像他没有登录)。

Solution n.1 解决方案n.1

The "redux way" would be to produce the full initial state on the server and serve it JSON.stringify({}) in your HTML like window.__REDUX_STATE__ = {...} . “ redux方式”将是在服务器上产生完整的初始状态,并在您的HTML之类的window.__REDUX_STATE__ = {...}为其提供JSON.stringify({})

This way your React App could boot synchronously. 这样,您的React App可以同步启动。

Solution n.2 解决方案2

If you really want it to be asynchronous and load the state from an API after the page loads, you could try to do something like: 如果您确实希望它是异步的并在页面加载从API加载状态,则可以尝试执行以下操作:

  1. fetch the full state (you also want to compose different sub-states... take a look at GraphQL!) and await the JSON response 获取完整状态(您还希望组成不同的子状态...查看GraphQL!),然后等待JSON响应
  2. boot your React App synchronously with the initial state 与初始状态同步启动您的React App

NOTE: I would go for n.1 as is the fastest when it comes to time to first meaningful frame. 注意:我会选择n.1,因为这是第一个有意义的帧时最快的。 Instagram does it that way :-) Instagram就是这样:-)

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

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