如何停止 React 页面重新渲染?

How can I stop React page to re-render?

我正在使用 fetch 从 API 获取数据。我正在为页面使用 useEffect 来停止重新呈现。但它不起作用

  const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }


  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);

从依赖项数组中删除 fetchPicth。如果您想将负载设置为 false,您可以这样做:

const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }


  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
    setLoad(false)
  };

  useEffect(() => {
     fetchPicth();
  }, []);

使用上面的代码只会从 API 中获取数据一次,即;挂载组件时。

这可以使用 2 种方法解决

  1. 在useEffect的依赖数组中传递状态

const [picth, setPicth] = useState([]);   // Initial state

 useEffect(() => {
    if (picth && picth.length !== 0) {   // Checks if data exists and length 
                                         //is greater than 0
      setLoad(false);                    // Set Loading to false
    }
  }, [picth]);


const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };
  1. 检查长度,没有数据则显示Progress。显示数据是否存在。

{picth.length === 0 && <div>Progress</div>}
      {picth.length > 0 && (
        <div>
          {picth.map((book, index) => {
            return (
              <YourComponent></YourComponent>
            );
          })}