【问题标题】:How delay redux saga action to store data update?如何延迟 redux saga action 来存储数据更新?
【发布时间】:2019-08-24 10:57:14
【问题描述】:

无法延迟操作触发(从 redux-form 初始化)以在获取后存储数据更新。

  1. Store 正在使用空帐户对象进行初始化。
  2. 在初始渲染时触发 getAccount 操作并触发存储更新。
  3. useEffect 查看商店更新和第二次触发 getAccount 操作
  4. 第二个数据请求
  5. 结束
  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]);
      

      【讨论】:

        猜你喜欢
        • 2021-07-01
        • 2018-10-19
        • 2018-06-18
        • 2015-07-19
        • 1970-01-01
        • 2018-09-21
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多