如何修复缺少的依赖项错误?使用useEffect React Hook时?

时间:2019-11-20 22:37:54

标签: javascript reactjs react-hooks

我的反应对象中存在依赖问题。

错误是“ React Hook useEffect缺少依赖项:'data'。要么包含它,要么删除依赖项arra”

import React, {useState, useEffect} from 'react';
import UrlInteligente from '../url';

const url = UrlInteligente.obtenerUrl("productos", "/productos");

export default function Productos(props){

    const [data, setData] = useState([]);
    const [hasError, setErrors] = useState(false);
    const [refresh, setRefresh] = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {  
        fetchApi();
        console.log("data esto " + data[0])
        setRefresh(false);
      }, [refresh]);


    async function fetchApi() {
        try {
          setLoading(true);
          const res = await fetch(url);
          await res.json()
            .then(json => { setData(json); console.log(json); });
        } catch (e) {
          setErrors(e);
        } finally {
          setLoading(false);
        }
      }

    return (
        <p> id :{data.id} </p>
    );
}

0 个答案:

没有答案