在React useEffect挂钩中设置挂钩状态

I'm trying to create a custom data fetching hook for a React assignment from one of my courses. Is's a simple hook accessing a couple of REST API endpoints and creating an inventory object which the app uses for a sallad composing component. The problem is that I can't seem to set the internal state of the hook from within the useEffect hook which fetches the data. I've used this approach many times before, and I have literally no idea what causes this behaviour. Wherever i try to use setContent inside my useEffect function, it always remains null.

请帮忙!

const useInventory = (baseURL) => {
    const [loading, setLoading] = useState(false);
    const [content, setContent] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        setContent(null);
        setLoading(true);

        const types = ['foundations', 'extras', 'proteins', 'dressings'];
        const urls = types.map(endp => `${baseURL}/${endp}`);

        Promise
            .all(urls.map(u => fetch(u)))
            .then(responses => Promise.all(responses.map(res => res.json())))
            .then(data => {

                const inventory = data.reduce((acc, curr, i) => 
                    ({ ...acc, [types[i]]: curr }),
                {});

                // This logs the inventory in desired format
                // e.g { foundations: Array, extras: Array, ... }
                console.log(inventory);
                setContent(inventory);
            })
            .catch(err => {
                setError(err);
            })
            .finally(() => {
                setLoading(false);

                // This logs null, for some reason
                console.log(content);
            });

    }, [baseURL]);

    return [content, loading, error];
}
评论