search

Home  >  Q&A  >  body text

Tips to use useEffect to maintain background color state

<p>I'm trying to save the background color of the wishlist toggle button so that when the user moves across pages, the color of the button remains "black" to show the user that they have saved the item to the wishlist. </p> <pre class="brush:php;toolbar:false;">const Item = (props) => { const dispatch = useDispatch(); const [background, setBackground] = useState(false); function addToCartHandler(product) { dispatch(addToCart(product)); } function toggleWishlistHandler(product) { dispatch(toggleItem(product)); setBackground((current) => !current); } return ( <div> <li className={classes.item}> <img src={props.img} alt="Item" className={classes.image} /> <div className={classes.description}> <p className={classes.title}>{props.title}</p> <p className={classes.price}>£{props.price}.00</p> </div> <div className={classes.actions}> <div className={`${classes.addWishlist} ${classes.icon}`} onClick={() => toggleWishlistHandler(props.product)} style={{ backgroundColor: background ? "black" : "orange", }} > <i className="fa-solid fa-heart"></i> </div> <div className={`${classes.addCart} ${classes.icon}`} onClick={() => addToCartHandler(props.product)} > <i className="fa-solid fa-bag-shopping"></i> </div> </div> </li> </div> ); }; export default Item;</pre>
P粉131455722P粉131455722468 days ago504

reply all(1)I'll reply

  • P粉642919823

    P粉6429198232023-08-19 00:09:28

    You can save colors in local storage.

    // 检查是否设置为黑色
      const [background, setBackground] = useState(localStorage.getItem('wishlistBackground') === 'black');
    
    
    // 每当背景颜色发生变化时,将其保存到本地存储中
      useEffect(() => {
        localStorage.setItem('wishlistBackground', background ? 'black' : 'orange');
      }, [background]);

    reply
    0
  • Cancelreply