【问题标题】:How delay redux saga action to store data update?如何延迟 redux saga action 来存储数据更新?
【发布时间】:2019-08-24 10:57:14
【问题描述】:
无法延迟操作触发(从 redux-form 初始化)以在获取后存储数据更新。
- Store 正在使用空帐户对象进行初始化。
- 在初始渲染时触发 getAccount 操作并触发存储更新。
- useEffect 查看商店更新和第二次触发 getAccount 操作
- 第二个数据请求
- 结束
const {getAccount, initialize} = props
prepareData = () => {...prepared obj}
useEffect(() => {
const begin = async () => {
await getAccount();
await initialize(prepareData());
};
begin();
}, [account.id]);
主要目的是避免不必要的第二次请求
【问题讨论】:
标签:
javascript
reactjs
react-redux
redux-form
redux-saga
【解决方案1】:
如果您对begin 调用设置条件会怎样?
const {getAccount, initialize} = props
const {begun, setBegun} = useState(false)
prepareData = () => {...prepared obj}
useEffect(() => {
const begin = async () => {
await setBegun(true);
await getAccount();
await initialize(prepareData());
};
begun || begin();
}, [account.id]);
【解决方案2】:
如果account.id 不存在,是否应该调用getAccount?如果没有,那么只需在调用 begin 之前检查 account.id 是否存在。
const {getAccount, initialize} = props
prepareData = () => {...prepared obj}
useEffect(() => {
// add a guard condition to exit early if account.id doesn't exist yet
if (!account.id) {
return;
}
const begin = async () => {
await getAccount();
await initialize(prepareData());
};
begin();
}, [account.id]);