繁体   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