简体   繁体   English

我无法在带有 Next.js 的 React.js 中使用状态变量中的 axios 填充请求响应

[英]I can't fill a request response using axios in state variable in React.js with Next.js

I'm working with React.js and I have the following problem:我正在使用 React.js,但遇到以下问题:

 import axios from "axios"; export default function Home() { const [products, setProducts] = useState([]); const ax = axios.create({ headers: { Accept: 'application/json' }}); function test() { const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => { // expected the setProducts to be filled with the return of this request setProducts(response.data); }); } test(); // and when I get here to see if the products have been filled, I get an empty array [ ] console.log(products); /* as the products variable was not filled within the axios promise by setProducts, there is no way to throw the products array here in the HTML to make a forEach or a map to look cute together with the tags */ return ( <sup>how sad, with the product array empty, I can't put the data here '-'</sup> ); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

See how the result comes out in the IDE console:查看结果如何在 IDE 控制台中显示:

在此处输入图像描述

I'm in Visual Studio not knowing what to do, I'm new to ReactJS with NextJS and from an early age I've been trying to see if I could solve this problem, but without success.我在 Visual Studio 中不知道该做什么,我是使用 NextJS 的 ReactJS 的新手,从很小的时候我就一直试图看看我是否可以解决这个问题,但没有成功。

What can I do to bring the products to the HTML page?如何将产品带到 HTML 页面?


UPDATE: As per the solution below, I created a possible workaround that indicates a path that could have returned a solution更新:根据下面的解决方案,我创建了一个可能的解决方法,指示可能返回解决方案的路径

 ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {}) .then((response) => setProducts(response.data)) .catch((error) => { console.log(error); // AxiosError {message: 'Network Error', name: 'AxiosError', ...} console.log(error.status); // undefined console.log(error.code); // ERR_NETWORK }); useEffect(() => { console.log(products); }, []);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.2/umd/react-dom.production.min.js"></script>

and I'm getting the same error that I put in the comments of the first answer below:我得到了与下面第一个答案的评论中相同的错误:

在此处输入图像描述

but when I change the setProducts by the console.log to see if it returns the same result, this appears in the terminal where my next.js application is running但是当我通过console.log更改setProducts以查看它是否返回相同的结果时,这会出现在我的 next.js 应用程序正在运行的终端中

that:那:

ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {})
.then((response) => console.log(response.data.length)) // returns the length of the products array

returns this when I update my app:当我更新我的应用程序时返回这个:

在此处输入图像描述

NOTE: That's why I'm not able to understand my application in Next.js.注意:这就是我在 Next.js 中无法理解我的应用程序的原因。 I'm following all the correct guidelines, writing the code perfectly using axios and when I run the application on the website it gives a network error and doesn't show exactly the amount of products that were displayed in the terminal where my application is running.我遵循所有正确的指导方针,使用 axios 完美编写代码,当我在网站上运行应用程序时,它会出现网络错误,并且没有准确显示在我的应用程序运行的终端中显示的产品数量.

I've already configured all the request headers correctly, enabling CORS to allow external requests with other API's, and I still don't succeed in returning the data to my application's page.我已经正确配置了所有请求标头,使 CORS 允许使用其他 API 进行外部请求,但我仍然无法成功将数据返回到我的应用程序页面。

Wrap the stuff you have to fetch products inside useEffect hook将您必须在 useEffect 钩子中获取产品的东西包装起来

useEffect(()=>{ 
const ax = axios.create({ headers: { Accept: 'application/json' }});


function test() {
    const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => {
        // expected the setProducts to be filled with the return of this request
        setProducts(response.data);
console.log(response.data)
    });
}
test();
},[])

Then in your return of the component, you can use map on products array with null and undefined checks Like然后在您返回组件时,您可以在 products 数组上使用带有 null 和未定义检查的 map 就像

{products && products.map(product=>{})} {products && products.map(product=>{})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM