简体   繁体   English

我如何在 React 中运行另一个 function ?

[英]How do I run one function after another one in React?

In my code, I have loadData() and useFilter() .在我的代码中,我有loadData()useFilter() I tried to run loadData() first as productsData need to be set for useFilter() to process productsData .我尝试先运行loadData() ,因为需要为useFilter()设置productsData来处理productsData However, I tried .then() but it still gives me undefined when I console log useFilter() How do I fix this?但是,我尝试了.then()但是当我控制台日志useFilter()时它仍然给我undefined我该如何解决这个问题?

  const [productsData, setProductsData] = useState(null);

  const loadData = async () => {
    const { data } = await getAxios().get('/market/list').then(response => response.data)
    setProductsData(data)
  }

  const useFilter = () => {
    return productsData.map(data => (...))
    //filters productsData
  };

  useEffect(()=>{
    loadData().then(()=>useFilter());
  },[])

Changing state asynchronous .更改 state异步 So using state immediately after changing that may not be updated one.所以在更改后立即使用 state 可能不会更新一个。

You can use useEffect to call your function after state changed.在 state 更改后,您可以使用useEffect调用您的 function。

You can do this:你可以这样做:

const [productsData, setProductsData] = useState(null);

const useFilter = () => {
  return productsData.map(data => (...))
  //filters productsData
};

useEffect(()=>{
  const loadData = async () => {
    const { data } = await getAxios().get('/market/list').then(response => response.data)
    setProductsData(data)
  }
  loadData()
},[])

useEffect(()=>{
  useFilter();
},[productsData])

Hello just by making a function async doesn't make it return a promise in order to use.then on function calls you must make sure they return promises您好,仅通过进行 function 异步不会使其返回 promise 以便使用。然后在 function 调用上,您必须确保他们返回承诺

So one implementation you could do is:所以你可以做的一种实现是:

    const [productsData, setProductsData] = useState(null);

  const loadData = () => {
    return getAxios().get('/market/list').then(response => response.data)
  }

  const useFilter = () => {
    return productsData.map(data => (...))
    //filters productsData
  };

  useEffect(()=>{
    loadData().then((data)=>{
    setProductsData(data);
    useFilter();
    }
   );
  },[])

In the above implementation I return the promise that axios returns you can also return your own promise by creating a promise using new Promise() constructor在上述实现中,我返回 axios 返回的 promise 您也可以通过创建 promise 来返回您自己的 promise

Do let me know if you face any issues如果您遇到任何问题,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM