【问题标题】:Saving data to redux vs making API calls to backend将数据保存到 redux 与对后端进行 API 调用
【发布时间】:2021-09-06 14:15:24
【问题描述】:

所以我有一个依赖于 redux-thunk 和 express 后端的应用程序。同时获取数据和发出发布请求是否被认为是一种好习惯?

这是一个代码示例:

export const getProducts = () => async (dispatch) => {
  const { data } = await API.getProducts();
  dispatch({ type: 'GET_PRODUCTS', payload: data });
};

export const createProduct = (proData) => async (dispatch) => {
  const { data, status } = await API.createProduct(proData);
  if (status === 200) {
    dispatch(getProducts());
  }
};

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    是的,大多数情况下都可以。

    您还可以考虑在您的 express api 的响应中返回新产品,并在 createProduct 完成后将其添加到 redux,如下所示:

    export const createProduct = (proData) => async (dispatch) => {
      const { data, status } = await API.createProduct(proData);
      if (status === 200) {
        // add product to state
        dispatch(productCreated(data));
      }
    };
    

    更高级的选项是通过在请求完成之前调度事件来乐观地更新您的商店(和 UI)。

    export const createProduct = (proData) => async (dispatch) => {
      dispatch(productCreatedPending(proData));
      const { data, status } = await API.createProduct(proData);
      if (status !== 200) {
        // Handle error by dispatching another action to fix the state
        // or however you want
      }
    };
    

    取决于你希望你的用户界面如何工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 2018-10-30
      • 2018-06-12
      相关资源
      最近更新 更多