【问题标题】:React Redux and FetchReact Redux 和 Fetch
【发布时间】:2019-10-22 16:28:08
【问题描述】:

我有带有 Redux 的 React 应用程序,其结构如下:

<ComponentParent>
<ComponentA></ComponentA>
<ComponentB></ComponentB>
</ComponentParent>

在组件 A 的 ComponentDidMount 中,调用 fetch 并异步返回数据。然后调用 Reducer 将数据添加到存储中。 然后组件 B 访问 store 以访问 A 添加到 store 中的数据。

可以预见的是,组件 B 在组件 A 发生更改以将数据写入存储之前访问数据(因为数据来自 aync fetch)。

问题:

  1. 设计这种交互的正确方法是什么?
  2. 我需要使用吗 方法类似于 react redux with asynchronous fetch ?请注意,在 Reducer 中,我只存储由异步返回的数据 组件 A,与链接中的不同

谢谢

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    为您的 componentB 设置默认状态,以便在等待获取结果时加载它。

    在您的 fetch 操作中,假设您使用 redux-thunk:

    let fetchData = () => async dispatch => {
     let res = await fetchFromDataSource();
     dispatch({
      type: UPDATE_STATE,
      payload: res
     }) 
    };
    

    您的组件 B 应该链接到商店。在调度更新时,它应该触发您的 componentB 通过 ComponentDidUpdate 重新加载。

    【讨论】:

    • 谢谢。我不想使用 await 思想,因为它会阻塞。我会尝试 Steven 的方法,但首先我需要思考一下 thunk
    • Tunk(没有等待)是答案:daveceddia.com/where-fetch-data-redux
    【解决方案2】:

    我喜欢在 reducer 中为对象创建初始状态的模式,这样访问它的任何组件都会首先获得该初始状态,然后可以根据获取后的状态进行更新。

    xReducer.js

    const initState = {
      // Initial state of object
    };
    export default function xReducer(state=initState, action) {
      switch (action.type) {
        case actionTypes.MY_POST_FETCH_ACTION_TYPE:
          return {
              ...state,
              // state override
          };
          default:
            return state;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 2016-04-07
      • 2017-06-12
      • 1970-01-01
      • 2018-08-06
      • 2017-10-04
      • 1970-01-01
      • 2016-12-10
      • 2018-08-06
      相关资源
      最近更新 更多