为什么React在使用map函数时不渲染任何东西?

0 javascript reactjs fetch-api

我想返回并渲染<li>包含所获取商店标题的元素,但只有<li>组件中的项目符号显示,没有内容。

import { useEffect, useState } from "react";

export default function Home() {
    const [stores, setStores] = new useState(null);
    const [error, setError] = new useState(null);
    const [isLoading, setIsLoading] = new useState(true);

    useEffect(() => {
        const getStores = async () => {
            try {
                const response = await fetch("https://www.cheapshark.com/api/1.0/stores");
                if (!response.ok) throw new Error(`Error: ${response.status}`);

                let data = await response.json();
                console.log(data);
                setStores(data);
                setError(null);
            }
            catch(err) {
                setError(err.message);
                setStores(null);
            }
            finally {
                setIsLoading(false);
            }  
        }
        
        getStores()
    }, []);

    return (
        <>
            <h1>Stores</h1>
            {isLoading && <div>A moment please...</div>}
            {error && <div>{`Error while fething data from API: ${error}`}</div>}

            <ul>
                {stores &&
                stores.map(store => (
                    <>
                        <li key={store.storeID}>{store.storeName}</li>
                        <img src={store.images.banner} />
                    </>
                ))}
            </ul>
        </>
    );
Run Code Online (Sandbox Code Playgroud)

我多次尝试重写map函数,但没有成功。这是我第一次使用 React,所以我不知道我可能做错了什么。

谢谢您的回答。

Joh*_*efs 5

new您的useState.

所以而不是:

  const [stores, setStores] = new useState(null);
Run Code Online (Sandbox Code Playgroud)

你应该使用:

  const [stores, setStores] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
Run Code Online (Sandbox Code Playgroud)