【问题标题】:React: How can I call these functions in useEffect conditionally inside my component?React:如何在组件内部有条件地调用 useEffect 中的这些函数?
【发布时间】:2021-09-10 03:29:00
【问题描述】:

我正在尝试实现此逻辑以有条件地从 API 中获取,我在 useEffect 挂钩中创建了获取逻辑,但我无法在我的组件中调用它们。 这样做的正确方法是什么。 或者我还有什么其他方法可以做到这一点?

对于 getF1、GetF2、getF3 函数,我使用了 try-catch 块,没有显示完整的代码

const myComponent = () => {
  
  const [info, setInfo] = useState([]);
  let venueName;
  let cId;

  useEffect(() => {
    const getTData = async (tid) => {
      try {
        const response = await axios.get(url);
        return response.data;
      } catch (error) {
        console.error(error);
      }
    };

    const getCC = async (tid) => {
      const t2data = await getTData(tid);
      cId = t2data?.xyz;
      console.log(cId);
    };
    getCC(tid);

    async function getF1() {
        const response = await fetch(url1);
    }

    async function getF2() {
        const response = await fetch(url2);
    }
    async function getF3() {
        const response = await fetch(url3);
    }

    getF1();
  }, []);

  const mainF = () => {
    let res1 = info.filter((x) => x.fields.travelId == tid);
    if (res1.length != 0) {
      linkValue =
        res1[0].a != undefined
          ? res1[0].a
          : res1[0].b != undefined
          ? res1[0].b
          : getF2();
      let res2 = info.filter(
        (x) => x.fields.colorId == cId
      );
      if (res2.length != 0) {
        linkValue =
          res2[0].a != undefined
            ? res2[0].a
            : res2[0].b!= undefined
            ? res2[0].b
            : getF3();
        let res3 = info.filter((x) => x.fields.venue == venueName);
        if (res3.length != 0) {
          linkValue =
            res3[0].a != undefined
              ? res3[0].a
              : "www.google.com";
        }
      }
    }
    return linkValue;
  };

  let finalValue = mainF();

【问题讨论】:

  • 在 useEffect 之外创建函数,然后从 useEffect 内部调用。像这样 useEffect(() => { getCC(tid); getF1(); },[]) 另外,不确定,但我认为你需要在 state 中存储场地名称、cId。
  • 我也应该在 useEffect 之外制作 getF2、getF3 吗?我在 mainF(); 内有条件地调用它们;
  • 是的,您可以尝试使用它。否则我认为它会出现编译错误,例如未定义函数。

标签: reactjs react-hooks fetch jsx use-effect


【解决方案1】:

尝试设置实例并使用实例调用该函数。

const myComponent = () => {
  
  const [info, setInfo] = useState([]);
  let venueName;
  let cId;
  const instance = this;
   
  const getTData = async (tid) => {
      try {
        const response = await axios.get(url);
        return response.data;
      } catch (error) {
        console.error(error);
      }
    };

    const getCC = async (tid) => {
      const t2data = await getTData(tid);
      cId = t2data?.xyz;
      console.log(cId);
      return cId;
    };
   

    async function getF1() {
        const response = await fetch(url1);
    }

    async function getF2() {
        const response = await fetch(url2);
    }
    async function getF3() {
        const response = await fetch(url3);
    }

  useEffect(() => {
    getCC(tid);
    getF1();
  }, []);

  const mainF = () => {
    let res1 = info.filter((x) => x.fields.travelId == tid);
    if (res1.length != 0) {
      linkValue =
        res1[0].a != undefined
          ? res1[0].a
          : res1[0].b != undefined
          ? res1[0].b
          : instance.getF2();
      let res2 = info.filter(
        (x) => x.fields.colorId == cId
      );
      if (res2.length != 0) {
        linkValue =
          res2[0].a != undefined
            ? res2[0].a
            : res2[0].b!= undefined
            ? res2[0].b
            : instance.getF3();
        let res3 = info.filter((x) => x.fields.venue == venueName);
        if (res3.length != 0) {
          linkValue =
            res3[0].a != undefined
              ? res3[0].a
              : "www.google.com";
        }
      }
    }
    return linkValue;
  };

  let finalValue = mainF();

【讨论】:

  • 试过了,显示“TypeError: Cannot read property 'getF2' of undefined”
【解决方案2】:

我认为你应该在 useEffect 之外调用所有函数,然后你可以在组件内的任何地方使用它们。如果你只想要来自 api 的结果,而不是返回,我建议你将它们存储在一个状态中并在组件中使用它们。

【讨论】:

    【解决方案3】:

    您可以将函数保留在外部或 useEffect 中,然后有条件地在 useEffect 中调用它们。你甚至可以将你的 useEffect 分开用于不同的功能。如果每个函数都有单独的依赖列表。

    const myComponent = () => {
      
      const [info, setInfo] = useState([]);
    
    const [function1Success, setFunction1Success] = useState(false);
    const [function2Success, setFunction2Success] = useState(false);
    const [function3Success, setFunction3Success] = useState(false);
    
    
      let venueName;
      let cId;
    
      const function1 = async() => {
            const response = await fetch(url1);
            if (condition to find response is success){
            setFunction1Success(true);
            }
        }
    
      const function2 = async() => {
            const response = await fetch(url1);
     if (condition to find response is success){
                setFunction2Success(true);
                }
        }
    
      const function2 = async() => {
            const response = await fetch(url1);
     if (condition to find response is success){
                setFunction3Success(true);
                }
        }
    
    
     
    // ADD THE BELOW CODE
    
    useEffect(() => {
    if(cond)function1();
    }, [])
    
    useEffect(() => {
    if(cond && function1Success)function2();
    }, [function1]) // Here
    
    useEffect(() => {
    if(cond && function2Success)function3();
    }, [function2]) // Here
    
      const mainF = () => {
        let res1 = info.filter((x) => x.fields.travelId == tid);
        if (res1.length != 0) {
          linkValue =
            res1[0].a != undefined
              ? res1[0].a
              : res1[0].b != undefined
              ? res1[0].b
              : getF2();
          let res2 = info.filter(
            (x) => x.fields.colorId == cId
          );
          if (res2.length != 0) {
            linkValue =
              res2[0].a != undefined
                ? res2[0].a
                : res2[0].b!= undefined
                ? res2[0].b
                : getF3();
            let res3 = info.filter((x) => x.fields.venue == venueName);
            if (res3.length != 0) {
              linkValue =
                res3[0].a != undefined
                  ? res3[0].a
                  : "www.google.com";
            }
          }
        }
        return linkValue;
      };
    
      let finalValue = mainF();
    

    更新:只有在function2执行成功后才调用function1,以此类推..

    然后,您可以为每个调用使用单独的 useEffect。并为每个函数定义状态,如上面的代码function1Success | function2Success | function3Success

    如果一个函数被执行并且结果是成功的。然后您可以将该特定函数的状态更新为 true。就像function1 是成功一样,您将function1Success 的状态变为true。

    并且由于在带有function2的useEffect的依赖列表中添加了function1Success,接下来会执行function2。以此类推。

    我们甚至在执行 function2Success 之前检查 function1Success 是否为真。

    【讨论】:

    • 我的条件取决于调用前一个函数的结果。例如:首先我想先调用 function1(),如果它给我未定义或空的结果,然后我调用 function2() 来获取,依此类推……在这种情况下,我该怎么做,有什么建议吗?
    • 我试过了,但它进入了一个无限循环并不断打印'finalValue'的值
    • @Aishwariya 你能分享你的代码吗?你试过什么?
    猜你喜欢
    • 2019-12-28
    • 2022-01-24
    • 2021-02-21
    • 2019-04-14
    • 2021-12-03
    • 1970-01-01
    • 2021-12-07
    • 2023-01-12
    • 2020-05-22
    相关资源
    最近更新 更多