In React useEffect does not update after the value has changed from other component

耗尽温柔 提交于 2020-03-16 06:48:07

问题


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).

I created a Cart Items service where I put all my added items, and it also has functions to addItem, removeItem, getCart, getCartSize.

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?

This is what I have done already.

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 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;
}



回答1:


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()

The code was calling also the function like getTotalCount() but only the name is needed, you don't need to call that.

I hope that helps!



来源:https://stackoverflow.com/questions/59198761/in-react-useeffect-does-not-update-after-the-value-has-changed-from-other-compon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!