【问题标题】:Redux - how to tell the difference between unloaded content and content that doesn't exist in the back-end?Redux - 如何区分卸载的内容和后端不存在的内容?
【发布时间】:2020-11-11 10:46:12
【问题描述】:

在 redux 商店中,例如,如果我将客户数据存储为:

{
  data: [1, 2, 3],
  customers: {
    1: { ... },
    2: { ... },
    3: { ... }
  }
}

在一个组件中,当我尝试显示 ID 为 4customer 时,看到该客户在商店中不存在,我将尝试使用 API 调用获取该客户。现在,假设客户4 实际上不存在于后端数据库中。在 API 调用结束时,store 被更新,customer 4 仍然不在 store 中。

我的问题是,从组件来看,这并没有告诉我客户是否尚未加载(在这种情况下我需要再次加载),或者客户实际上不存在于后端数据库(在这种情况下,我需要显示适当的消息)。这在 Redux 中通常是如何处理的?

【问题讨论】:

  • 您可以在您的 redux-store 中为每个客户添加 loaded 标志 true/false

标签: redux react-redux


【解决方案1】:

您可能希望将 error 字段添加到 redux 存储区。如果在 DB 中找不到客户,则在进行 API 调用时更新错误。

{
  data: [1, 2, 3],
  customers: {
    1: { ... },
    2: { ... },
    3: { ... }
  },
  error: null,
}
// api.js
fetch("backend-url.com/customer/4")
  .then(res => res.json)
  .then(result => {
    // don't forget to clear the error in the reducer
    dispatch(addCustomer(result));
  })
  .catch(err => {
    // No customer found
    dispatch(storeError(err));
  });

然后在组件中

// component.js

...

const { customers, data, error } = useReduxStore();

return (
  <div>
    { error ? <Error message={error} /> : <Customers customers={customers} /> }
  </div>
); 

【讨论】:

  • 如果 api 调用未能返回客户(因为它不存在)......它不会触发错误来捕获......
【解决方案2】:

您可以在加载客户后签入您的组件,如果客户是空对象 {} ... 那么它已加载但不存在,如果它是 null ... 那么您需要触发加载它的 redux 操作...

- 如果您收到 error ...,那么您可能会显示一般错误消息,例如 出了什么问题,这可能是互联网连接问题或后端内部问题

export const getCustomer = () => dispatch => {
  dispatch({ type: 'GET_CUSTOMER_START' });

  axios
    .get('your api end point')
    .then(res => {
      const customer = res.data;

      dispatch({
        type: 'GET_CUSTOMER_SUCCESS',
        payload: {
          customer: customer || {},
        },
      });
    })
    .catch(error => {
      dispatch({
        type: 'GET_CUSTOMER_FAIL',
        payload: { error },
      });
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    相关资源
    最近更新 更多