在 React 中 useEffect 在值从其他组件更改后不会更新 [英] In React useEffect does not update after the value has changed from other component
问题描述
我正在尝试为自己开设某种在线商店,但遇到了问题.我想在 NavBar
组件(每个页面上都有)中呈现我的购物车大小.
I am trying to do some kind of online shop for myself and I got a problem.
I want to render my shopping cart size in the NavBar
component (which is on every page).
我创建了一个 Cart Items 服务,用于放置我添加的所有项目,它还具有 addItem
、removeItem
、getCart
、getCartSize
.
I created a Cart Items service where I put all my added items, and it also has functions to addItem
, removeItem
, getCart
, getCartSize
.
当我单击特定产品上的添加/删除时,我希望 NavBar
上带有购物车大小的值会根据购物车大小(来自 getCartSize代码>方法).我已经尝试使用
useEffect
钩子,但它无法识别 cartSize
的值何时更改,我该怎么做?
When I click on Add/Remove on specific product, I would like to do that the value on NavBar
with cart size would be changing depending on the cart size (from getCartSize
method). I already tried to use useEffect
hook, but it does not recognize when the value of cartSize
is changed, how can I do that?
这是我已经完成的.
navbar.jsx
:
//...
//...
import {getTotalCount} from '../../services/myCart';
export default function Navbar() {
// ...
const [count, setCount] = useState();
useEffect(() => {
setCount(getTotalCount());
console.log('counto useeffect');
},[getTotalCount()]);
return (
<>
<header className="navbar">
<Link className="navbar__list-item__home-icon" to="/"><span><FaHome/></span></Link>
<Link className="navbar__list-item" to="/products">Products</Link>
<h2>cart size--> {count}</h2>
<Link className="navbar__list-item__cart-img" to="shopping-cart"><span><FaShoppingCart/></span></Link>
</header>
</>
);
}
myCart.js
所有功能都可以正常工作,当我在产品页面的组件上单击添加/删除按钮时,我会调用它们.
myCart.js
all functions work fine and I call them when I click add/remove button in on my component in the products page.
var InTheCart = [
];
var totalCount = 0;
export function AddToCart(item) {
// ... logic
totalCount++;
}
export function ContainsInTheCart(id) {
return InTheCart.findIndex(x=> x.item.id == id) != -1 ? true: false;
}
export function RemoveFromCart(id) {
// ... logic
totalCount--;
}
export function getCart() {
return InTheCart;
}
export function getTotalCount() {
return totalCount;
}
推荐答案
在依赖数组中只需要传递函数名即可,如下所示:
In the dependency array you need to pass only the name of the function, just like below:
useEffect(() => {
setCount(getTotalCount());
console.log('count useEffect');
}, [getTotalCount]); // not like => getTotalCount()
代码也调用了像 getTotalCount()
这样的函数,但只需要名字,你不需要调用它.
The code was calling also the function like getTotalCount()
but only the name is needed, you don't need to call that.
希望能帮到你!
这篇关于在 React 中 useEffect 在值从其他组件更改后不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!