reactjs - 在 Redux 中获取初始状态

标签 reactjs redux react-redux

我正在构建一个应用程序,在安装主要组件之前,我需要从服务器获取初始 redux 状态。 在我的操作中,我使用 redux-thunk 来获取必要的数据:

export const getInitialStateSuccess = (state: any): IfetchThemeSuccess => {
    console.log('state', state);
    return {
        type: FETCH_INIT_STATE,
        state
    };
};


// here I fetch the data from the server and call getInitialStateSuccess
// to pass it to redux init state
export const getInitialState = () => {
     return (dispatch: any) => {
         api.getInitState().then((data) => {
              dispatch(getInitialStateSuccess(data));
          });
      };
 }

但是,我不知道应该在哪里调用 getInitialState()。我需要在安装主要组件之前初始化应用程序的状态。您认为在 componentWillMount 中调用此操作是一个好习惯吗?它只需调用一次。 请让我知道我上面描述的方法是否是一个好的做法。 谢谢!

最佳答案

您可以在 WillMount 中调用它,但首选 DidMount 。这是因为如果您有服务器端渲染,WillMount 可以调用两次。

无论哪种方式,您都需要事先有一个中间“加载”屏幕,因为调用是异步的,并且它将在数据加载之前呈现。

关于reactjs - 在 Redux 中获取初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911013/

相关文章:

javascript - React useReducer 调度在使用 fetch 请求后不会重新渲染组件

javascript - 更改/添加 index.js 的 create-react-app 入口点或位置

javascript - Typescript 错误 "Property ' then' does not exist"when chaining promises with promise-middleware + thunk

reactjs - 警告 : Invalid value for prop `dispatch` on <span> tag

reactjs - React setState() 回调问题,无法访问输出变量

reactjs - 父子组件中的 MapStateToProps 和 MapDispachToProps 不起作用

javascript - js文件类型错误: Dispatch is not a Function in actions.

javascript - React Virtualized 抛出错误 - TypeError : _reactVirtualized2. 默认未定义

javascript - [React]容器组件设计

javascript - forEach() 不会更新数据库调用内的值