在 redux store 中,例如,如果我将客户数据存储为:
{
data: [1, 2, 3],
customers: {
1: { ... },
2: { ... },
3: { ... }
}
}
在组件中,当我尝试显示 ID 为 4
的 customer
时,发现商店中不存在该客户,我将尝试获取该客户使用 API 调用。现在,假设客户 4
实际上不存在于后端数据库中。 API 调用结束时,商店已更新,客户 4
仍不在商店中。
我的问题是,从组件来看,这并没有告诉我客户是否还没有加载(在那种情况下我需要重新加载),或者客户实际上不存在于后端数据库(在这种情况下,我将需要显示适当的消息)。这在 Redux 中通常是如何处理的?
最佳答案
您可能希望将 error
字段添加到 redux 存储中。如果在数据库中找不到客户,则在进行 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>
);
关于Redux - 如何区分卸载的内容和后端不存在的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64784940/