结果在React.js陷入无限循环
The result fall into an infinite cycle in React.js
谁能帮我解决我的问题?我是 React.js 的初学者,我刚刚制作了组件来显示购物车结果!但不知为何,陷入了无限循环
发布截图:http://prntscr.com/1w5hbey
您可以通过此站点查看控制台数据 URL。谢谢
https://side-cart-react.myshopify.com/products/test2
import React, { useState } from "react"
import ReactDom from "react-dom"
const LineItem = (props) => {
return (
<div className="line-item" data-line="">
<div className="line-item__header">
<div className="line-item__title">
<p>{console.log(props.cart)}</p>
</div>
<p className="line-item__price"></p>
</div>
</div>
)
}
const CartDrawer = () => {
const [cart, setCart] = useState("");
const getCart = () => {
fetch("/cart.js", {
method: 'GET',
headers: new Headers({'content-type': 'application/json', 'X-Requested-With':'xmlhttprequest'})
}).then(res => {
return res.json();
}).then(json => {
setCart(json);
console.log('state',cart);
});
}
getCart();
return <LineItem cart={cart} />;
}
const root = document.getElementById('cart__drawer_items');
ReactDom.render(<CartDrawer />, root);
当您调用 setCart(json)
时,它会导致您的组件重新呈现。在随后的渲染中,您的函数 getCart()
再次被调用,因此您陷入了无限循环。相反,您应该像这样在 useEffect
内调用 getCart()
:
const CartDrawer = () => {
useEffect(() => {
getCart();
}, []);
return ...;
}
这样,它只会被调用一次。如果您希望购物车在某些状态或道具发生变化时更新,您应该将这些变量添加到 useEffect
依赖数组中。
谁能帮我解决我的问题?我是 React.js 的初学者,我刚刚制作了组件来显示购物车结果!但不知为何,陷入了无限循环
发布截图:http://prntscr.com/1w5hbey
您可以通过此站点查看控制台数据 URL。谢谢
https://side-cart-react.myshopify.com/products/test2
import React, { useState } from "react"
import ReactDom from "react-dom"
const LineItem = (props) => {
return (
<div className="line-item" data-line="">
<div className="line-item__header">
<div className="line-item__title">
<p>{console.log(props.cart)}</p>
</div>
<p className="line-item__price"></p>
</div>
</div>
)
}
const CartDrawer = () => {
const [cart, setCart] = useState("");
const getCart = () => {
fetch("/cart.js", {
method: 'GET',
headers: new Headers({'content-type': 'application/json', 'X-Requested-With':'xmlhttprequest'})
}).then(res => {
return res.json();
}).then(json => {
setCart(json);
console.log('state',cart);
});
}
getCart();
return <LineItem cart={cart} />;
}
const root = document.getElementById('cart__drawer_items');
ReactDom.render(<CartDrawer />, root);
当您调用 setCart(json)
时,它会导致您的组件重新呈现。在随后的渲染中,您的函数 getCart()
再次被调用,因此您陷入了无限循环。相反,您应该像这样在 useEffect
内调用 getCart()
:
const CartDrawer = () => {
useEffect(() => {
getCart();
}, []);
return ...;
}
这样,它只会被调用一次。如果您希望购物车在某些状态或道具发生变化时更新,您应该将这些变量添加到 useEffect
依赖数组中。