我想停止在 react-hooks 中渲染

I want stop rendering in react-hooks

正在继续渲染。我想阻止它。

由于这个问题,从 Api 收到的照片和文字一直在随机变化。

我认为 useEffect 是问题所在。请让我知道,因为我是初学者。

这是useFetch.jsx

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  });
  return [data, loading];
}
export default useFetch;

这是Main.jsx

import React from "react";
import styled from "styled-components";
import useFetch from "./useFetch";
import "./font.css";

const url = "https://www.thecocktaildb.com/api/json/v1/1/random.php";
const Main = () => {
  const [data, loading] = useFetch(url);
  return (
    <Wrapper>
      <Header>My Cocktail Recipe</Header>
      {loading ? (
        "Loading..."
      ) : (
        <>
          {data.drinks.map(
            ({ idDrink, strDrink, strAlcoholic, strGlass, strDrinkThumb }) => (
              <Container>
                <img src={`${strDrinkThumb}`} alt="" />
                <div key={`${idDrink}`}>{`${strDrink}`}</div>
              </Container>
            )
          )}
        </>
      )}
      <Search type="text" placeholder="검색하세요" val />
    </Wrapper>
  );
};
export default Main;
useEffect(() => {
    fetchUrl();
  }, []);
  return [data, loading];
}

添加数组感谢 Nick Parsons

你必须更新useFetch.jsx:

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false);
  }

  useEffect(() => {
    fetchUrl();
  }, []); //<--- Here

  return [data, loading];
}
export default useFetch;

问题是 useEffect 挂钩接收两个参数,而您忘记了第二个参数,即效果的依赖项数组。