【问题标题】:Redux - get initial state from the backend - which is the proper way to do it?Redux - 从后端获取初始状态 - 这是正确的方法吗?
【发布时间】:2019-05-12 21:50:57
【问题描述】:

我想从后端(即showTutorial)获取一些变量,用于reducer 中的初始状态。

我在考虑只使用 reducer 在 axios 中的调用,但我不确定这是否是最好的方法。

现在是这样完成的:

import { UNSET_TUTORIAL, SET_FILTER_BLOCKS } from "../actions/types";


const initialState = {
  showTutorial: true, // <-- instead of initializying to true, do the axios call
  filterBlocks: "ALL"
};

export default (state = initialState, action) => {
  switch (action.type) {
    case UNSET_TUTORIAL:
          return { ...state, showTutorial: false };

    case SET_FILTER_BLOCKS:
      return { ...state, filterBlocks: action.payload };
    default:
      return state;
  }
};

我不想使用 redux-persist,因为我想先了解正确的做法。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    执行此操作的方式与从后端为任何其他组件更新状态的方式没有区别。

    您应该在顶级应用组件(或在应用启动时创建的任何组件)上触发一个操作,该组件从后端加载数据并使用来自后端的结果分派该操作。然后你的 reducer 会根据这个动作更新状态。

    可以在组件挂载时使用生命周期事件来触发顶级应用组件上的操作,通常是getDerivedStateFromProps()

    【讨论】:

      【解决方案2】:

      最好的方法是从 App.js 调用相关操作,并渲染“加载”,直到正确获取数据。显然,如果出现错误,您将不会继续渲染组件,而是显示错误消息。

      Reducer 永远不应该调用 action,这会破坏 redux 流程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多