I\'ve been building a Gutenberg Block that sends a GET
request to the Woocommerce REST API.
It is composed of a text input
that receives an ID of a product and fetches it to the Woocommerce REST API. It also has a button
that fires a function to fetch the product with the API.
The issue with the GET Requests
The fetching works well, but it keeps sending multiple GET
requests, even when I do not click the button to fire the function. Simply clicking the input sends multiple requests when I only need one everytime I change the ID and click the button.
I\'m importing WooCommerceRestApi
from "@woocommerce/woocommerce-rest-api"
and use Node.js.
The code
This is the first part of the edit function:
const edit = ({ attributes, setAttributes }) => {
const blockProps = useBlockProps();
// Wrapped the WooCommerce.get() function in a function named `fetchingId` to call it with a button
const fetchingId = async (id) => {
// The WooCoommerce.get() function
const response = await WooCommerce.get(`products/${id}`)
.then((response) => {
console.log(response.data);
setAttributes({ price: response.data.price });
setAttributes({ name: response.data.name });
})
.catch((error) => {
console.log(error.response.data);
setAttributes({ price: \'\' });
setAttributes({ name: \'\' });
});
}
...
}
This is another part of the function: an input that updates the Product ID
that is used for the GET
request and a button linked to the fetchingId()
function.
return <div {...blockProps}>
<div class="wrapper-input" >
<TextControl
label={__(\'ID du Produit\', \'ingredient-unique\')}
value={attributes.id}
onChange={(val) => setAttributes({ id: val })}
className=\'control-id\'
/>
</div>
<button onclick={fetchingId(attributes.id)}>Chercher le produit</button>
...
</div>;
最合适的回答,由SO网友:Tom J Nowell 整理而成
您不应该直接在React组件内发出HTTP请求等,您需要使用useEffect
.
react组件需要尽快运行,即使需要执行的工作尚未完成。通过使用useEffect
您告诉React在渲染完成后运行一个单独的函数,这样您就有机会发出请求并让您的组件;效果;。React还允许您传递它将监视的依赖项列表,如果它们更改了效果,则重新运行。
然而,您所拥有的是直接在组件中运行的副作用。因此,每当重新呈现组件时,您的代码都会进行HTTP获取,除此之外,这还会显著降低编辑器的速度。根据设计,可以随时进行重新渲染。窗口大小调整、游离dom事件、父组件中的状态更改等
如果有帮助的话,一种常见的方法就是这样:
const { isLoading, setLoading } = useState( false );
这样你就可以打电话
setLoading( false )
在您的
useEffect
函数,然后在组件中显示加载消息
这是该函数的另一部分:更新用于GET请求的产品ID的输入,以及链接到fetchingId()函数的按钮。
你不能指望这些价值观出现在这里。您可以通过事件触发一个函数,该函数可能会产生HTTP请求等副作用,但您不能直接在组件中执行这些操作。渲染组件应渲染组件,并且only渲染组件,其他一切都进入生命周期挂钩/功能