【问题标题】:React useeffect hook反应使用效果挂钩
【发布时间】:2020-04-02 05:50:24
【问题描述】:

使用挂钩获取数据时出现以下错误。 我有两个功能组件

function TopTen() {
    const [topTen, setTopten] = useState([]);  
    const [loading, setLoading] = useState(true); 
    const [error, setError] = useState(false); 

    useEffect(() => {         
        console.log("useEffect TopTen has been called!");   
        const fetchdata = async () => {
        const response = await api.topTen();  // this calls axios(url)
        setLoading(false);
        setTopten(response.data);    
        setError(response.error);    
    };

    fetchdata ();     
}, []);

  return ( 
        {topTen.length > 0 &&
        <Table 
          tableData={topTen.map((item, idx) => {
            return ([
              item.name
            ]);
          })}
        /> 
        }
    )

}

function Declaraciones() {

    // ... here I'm using other effects also for fetching data 
    const [data, setData] = useState([]);

    useEffect(() => {            
        const fetchData = async () => {
        const response = await api.fetch();
    //...
        };

        fetchData ();     
    }, []);

    return (

        <div>
            <p>{data}</p>
            <TopTen />
        </div>
    )

}

出于某种原因,TopTen 组件有时可以正常工作,有时却不能。这就像随机。 我看到的是 api 调用返回像“缓存”这样的假数据,所以当尝试映射结果时它失败了:

**TypeError: Cannot read property 'name' of undefined**

也许我错过了 useEffect 挂钩的概念。

有谁知道我该如何解决这个问题?

谢谢

【问题讨论】:

  • 您确定您的后端每次都发送一致的架构作为响应吗?
  • @UtsavPatel 是的,我正在用邮递员测试我的后端 API,它没问题。奇怪的是,有时当从前端发送请求时,它会返回好的结果和其他一些不好的结果。我不知道为什么。我正在调试 axios 请求,显然没问题
  • 当返回错误数据时,它属于我之前/之后正在执行的另一个获取请求,例如请求 1 => 数据 1 请求 2 => 数据 2 --- 这里我的后端返回数据 1请求 3 => 数据 3

标签: reactjs axios react-hooks


【解决方案1】:

您必须使用 await response.json(); 将响应转换为 json; 然后使用 setState。

useEffect(() => {         
        console.log("useEffect TopTen has been called!");   
        const fetchdata = async () => {
        const response = await api.topTen();  // this calls axios(url)
        const responseData = await response.json();
        setLoading(false);
        setTopten(responseData.data);    
        setError(responseData.error);    
    };

    fetchdata ();     
}, []);

【讨论】:

  • 我已经尝试同时使用 axios 和 fetch,现在我得到了很好的结果,但我不知道为什么有时它们会返回错误的数据` const result = await fetch('/api/path/最佳');常量 json = 等待结果.json();响应数据 = json; const result2 = await axios.get('/api/path/top'); response.data2 = 结果2.data; `
【解决方案2】:

试试:

setTopten(response.data.filter(function(val){ return val!==undefined; }))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2020-04-27
    • 2020-08-13
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多