簡體   English   中英

使用 Typescript 處理圖像 - NextJS

[英]Handling images with Typescript - NextJS

我有一個簡單的網站,它從 Spoonacular API 獲取數據並搜索成分,響應帶有標題和圖像。 我已將類型聲明為:

export interface IProps {
    id: number;
    name: string;
    image: string;
  }

到目前為止,我的成分清單如下:

const List = (props: { ingredient: IProps }) => {
  const { ingredient } = props;

  return (
    <Container>
      <Box>
        <Image src={ingredient.image} alt={ingredient.name} />
        <Box>
          {ingredient.name}
        </Box>
      </Box>
    </Container>
  );
};

export default List;

我已經刪除了與樣式相關的所有內容,僅供參考。

道具來自我打電話的地方:

const Search = () => {


  const [ingredients, setIngredients] = useState<IProps[]>([]);
  const [value, setValue] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    axios
      .get(
        `https://api.spoonacular.com/food/ingredients/search?query=${value}&number=2&apiKey=${URL}`
      )
      .then((res) => res.data)
      .then((data) => data.results)
      .then((data) => setData(data))
      .catch((err) => console.log(err));
  };

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <Flex justifyContent="center">
      <Flex direction="column">
        <Heading mb={6}>Search Recipe</Heading>
        <Input
          onChange={handleChange}
          value={value}
          name="search"
          id="search"
          placeholder="Write here..."
          variant="filled"
          mb={2}
          type="text"
        />
        <Button onClick={handleSubmit} mb={5}>
          Search
        </Button>
       
      </Flex>
      {ingredients.map((ingredient) => (
        <List key={ingredient.id} ingredient={ingredient} />
      ))}
    </Flex>
  );
};
export default Search;

但我沒有得到的是我從圖像中得到 404 的事實:

Request URL: http://localhost:3000/lemon.png
Request Method: GET
Status Code: 404 Not Found
Remote Address: 000.0.0.0:0000
Referrer Policy: strict-origin-when-cross-origin

由於我是 typescript 的新手,我可能錯過了一些非常基本的東西?

正在發生的事情是 API 只給你一個像lemon.png這樣的文件名。 To locate the image from the API, you need to append it to the string https://spoonacular.com/cdn/ingredients_100x100/ before passing it into the Image component ie in this case, you would end up with https://spoonacular.com/cdn/ingredients_100x100/lemon.png

您可以在此處找到有關從 API 獲取圖像的更多信息(鏈接到 Spoonacular API 文檔)

添加 Ritik Mishra 所說的內容,作為您和其他使用 Spoonacular 的人的示例,您的 src 看起來像:

src={`https://spoonacular.com/cdn/ingredients_250x250/${ingredient.image}`}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM