为什么我在chrome inspect ->网络中得到双重响应?

3wabscal  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(148)

This is what it look like
这是我的代码,你能帮我找到我做错了什么吗?我尝试了不同的事情,但它没有工作。照片和代码都给。

const ProductScreen = () => {
    const {id} = useParams();
    //const product = products.find((p) => p._id === id);

    const [product, setProduct] = useState({})

    useEffect(()=>{
        const fetchProducts = async () => {
          const {data} = await axios.get(`/api/products/${id}`)
    
          setProduct(data)
        }
    
        fetchProducts()
    }, [])
    
   // if(!product) return null;

   // return ( <div>{product.name}</div> );

   return (
    <>
     // I thing this part of the code is not responsible for the issue
    </>
   )

}

export default ProductScreen
xriantvc

xriantvc1#

在开发模式下使用React 18的Strict模式将导致all useEffect s to be called twice,从而导致您在此处看到的问题。
解决方法很简单:使用用于此任务库(如React Query):

/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import axios from "axios";

const queryClient = new QueryClient();

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Example />
    </QueryClientProvider>
  );
}

function Example() {
  const { isLoading, error, data, isFetching } = useQuery(["repoData"], () =>
    axios
      .get("https://api.github.com/repos/tannerlinsley/react-query")
      .then((res) => res.data)
  );

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{" "}
      <strong>✨ {data.stargazers_count}</strong>{" "}
      <strong>🍴 {data.forks_count}</strong>
      <div>{isFetching ? "Updating..." : ""}</div>
      <ReactQueryDevtools initialIsOpen />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.createRoot(rootElement).render(<App />);

相关问题