使用useEffect()并提取两次

时间:2020-10-26 15:02:50

标签: javascript reactjs react-hooks fetch

我正在将React Hooks与UseEffect一起使用,但是当我尝试记录响应时,得到的数组记录了两次。 如您所见,我在[]的末尾使用UseEffect。另外,当我在挂钩中打印某些内容时,它仅记录一次。

enter image description here

JobsApi.tsx

const url = "http://jobs.github.com/positions.json";

export function getJobs() {
    const proxyurl = "https://cors-anywhere.herokuapp.com/";

    return fetch(proxyurl + url)
    .then((response) => response.json())
    .then((responseJson) => {
        return responseJson;
    })
    .catch((error) => {
        console.error(error);
        return;
    });
}

Boxresult.tsx

import React, { useState, useEffect } from 'react';

import { getJobs } from '../../service/api/JobsApi';

const BoxResult = () => {
    const [fetchJobs, setFetchedJobs] = useState([]);
    useEffect(() => {
        const fetchAPI = async () => {
            console.log('ACAADADAS');
            setFetchedJobs(await getJobs());
        }

        console.log('i fire once');

        fetchAPI();
    }, [])

    console.log(fetchJobs);

    return (
        <div>
        ACA
            {/* {fetchedCountries.map((country, i) => <div key={i} value={country}>{country}</div>)} */}
        </div>
    )
}

export default BoxResult

0 个答案:

没有答案