useCallback 在按钮单击时获取数据

问题描述 投票:0回答:2

我有一个场景,我要在单击按钮时获取数据并将其存储在上下文变量中。请检查以下代码:

const [products, setProducts] = useState([]);

 const handleButtonClick= useCallback(() => {
    if (countryCode) {
      async function getproducts() {
        try {
          const apiData = await fetch(URL);
          const jsonData = await apiData.json();
          setProducts(jsonData);
        } catch (error) {
          console.error(error);
        }
      }
      getproducts();
    }
  }, [targetGroup,countryCode]);

我会在按钮 onClick() 上使用这个回调函数:

handleButtonClick()
。我对 React 还很陌生,有时我对 React hooks 感到困惑。这是正确的方法还是根本不需要回调函数,只需一个普通函数即可?

reactjs react-hooks fetch-api
2个回答
0
投票

这个函数不需要

useCallback
,你可以编写一个普通的函数并像这样使用它:

<button onClick={handleButtonClick}>Click me</button>


0
投票

我认为你的代码没问题,但我想重构你的代码。

import React from 'react';
import { getProducts } from '~/apis/product';

const SomeComponent = () => {
  const [products, setProducts] = React.useState([]);

  const handleButtonClick = React.useCallback(async ()=>{
    if(countryCode) {
       const _products = await getProducts();
       setProducts(_products);
     }
  }, [countryCode]); // I don't know what is countryCode but I guess it must be a state, so you need to add that.

  return (<div>Some Component</div>);
}
export default SomeComponent;

您可以将API函数和组件分开。 ~/apis/product.js

export async function getproducts() {
  try {
    const apiData = await fetch(`SOME YOUR URL`);
    const jsonData = await apiData.json();
    return jsonData;
  } catch (error) {
    console.error(error);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.