【问题标题】:Image display React API without URL没有 URL 的图像显示 React API
【发布时间】:2021-07-16 00:09:24
【问题描述】:

我已经观看了几十个 youtube 视频,但没有遇到我的问题。

在 React 中,我想显示一张来自 spoonacular API 的图片,我只能在控制台中获得“name.png”(即不是完整的 url)。

setPicture(result.data.results[0].image),我在控制台中得到了图片的名字,我只需要得到它前面的url。我尝试使用以下<img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food">; 进行此操作,并且还尝试将 url 放在 useState 中,但这不起作用。

我的完整代码如下:

    const [food, setFood] = useState([]);
    const [picture, setPicture] = useState([])

    useEffect(() => {
        async function fetchFood() {
            const result = await axios.get(`https://api.spoonacular.com/food/ingredients/search?query=rice&number=20&apiKey=${apiKey}`);
            console.log(result);
            console.log("DATA:", result.data);
            console.log("DATA RESULTS:", result.data.results);
            // console.log("DATA RESULTS[0]:", result.data.results[0]);
            // console.log("DATA RESULTS[0]:", result.data.results[0].title);
            setFood(result.data.results[0]);
            setPicture(result.data.results[0].image)
        }

        fetchFood();
    }, []);

    return (
        <div>
            <div>{food.name}</div>
            <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food">;
        </div>
    );
}

【问题讨论】:

    标签: reactjs image url spoonacular


    【解决方案1】:

    JSX 应该以 /&gt;(或 &gt;,如果它有孩子)而不是 &gt;; 关闭

    <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food" />
    

    如果只想显示一个元素,可以使用&gt;;,例如:

    function app() {
      return <img />;
    }
    

    它会起作用,因为它是return 的结尾。而且你已经拥有了。

    return (
      <div>
        <div>{food.name}</div>
        <img src={`https://spoonacular.com/cdn/ingredients_250x250/${picture}`} alt="food" />
      </div>
    ); // here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多