英文:
ReactJS how to render component when changes value
问题
以下是您要翻译的代码部分:
Header Page:
import React, { useContext, useState, useEffect } from 'react';
import { Container, Navbar, Nav } from 'react-bootstrap';
import { ThemeContext } from '../GlobalComponents/ThemeProvider';
import { BiSun, BiMoon, BiCart } from 'react-icons/bi';
import { VscAccount } from 'react-icons/vsc';
import { Link } from "@reach/router";
import { useCart } from "react-use-cart";
import { useAuth0 } from "@auth0/auth0-react";
const Header = () => {
const { theme, setThemeMode } = useContext(ThemeContext);
const [darkMode, setDarkMode] = useState(theme);
const { loginWithRedirect, logout, isAuthenticated, user, isLoading } = useAuth0();
const [count, setCount] = useState((JSON.parse(localStorage.getItem("liked"))));
const cou = () => {
let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
if (oldData.length === count.length) {
setCount((JSON.parse(localStorage.getItem("liked"))))
} else {
setCount((JSON.parse(localStorage.getItem("liked"))))
}
};
useEffect(() => {
let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
if (oldData.length === count.length) {
setCount((JSON.parse(localStorage.getItem("liked"))))
} else {
setCount((JSON.parse(localStorage.getItem("liked"))))
}
}, [count]);
useEffect(() => {
setThemeMode(darkMode);
console.log(darkMode)
}, [darkMode]);
const {
isEmpty,
totalItems,
} = useCart();
if (isLoading) {
return (
<Navbar collapseOnSelect expand="md"
variant={darkMode ? 'dark' : 'light'}
className={darkMode ? 'bg-light-black border-bottom' : 'bg-light border-bottom'}
style={{ width: '100%', position: 'fixed', zIndex: 100 }}
>
<Container>
<Link to="/">
<Navbar.Brand className={darkMode ? 'text-dark-primary' : 'text-light-primary'}>
<img src='https://i.ibb.co/7kZrn4H/33342.png' width={200} />
</Navbar.Brand>
</Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ms-auto">
<div className='load'><div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div></div>
<Nav.Link
className={darkMode ? 'text-dark-primary' : 'text-light-primary'}
onClick={() => setDarkMode(!darkMode)}
>
{darkMode ? <BiSun size="1.7rem" /> : <BiMoon size="1.7rem" />}
</Nav.Link>
<Link
to="/cart"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{totalItems}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}> Cart</span>
</Link>
<Link
to="/wishlist"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{count.length}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}> Wishlist</span>
</Link>
{
isAuthenticated ? (
<>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log Out
</button>
</>
) : (
<>
<button onClick={() => loginWithRedirect()} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log in
</button>
</>
)
}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
return (
<Navbar collapseOnSelect expand="md"
variant={darkMode ? 'dark' : 'light'}
className={darkMode ? 'bg-light-black border-bottom' : 'bg-light border-bottom'}
style={{ width: '100%', position: 'fixed', zIndex: 100 }}
>
<Container>
<Link to="/">
<Navbar.Brand className={darkMode ? 'text-dark-primary' : 'text-light-primary'}>
<img src='https://i.ibb.co/7kZrn4H/33342.png' width={200} />
</Navbar.Brand>
</Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ms-auto">
{
isAuthenticated && (
<>
<p className={`d-flex align-items-center user-name ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>{user.email}</p>
</>
)
}
<Nav.Link
className={darkMode ? 'text-dark-primary' : 'text-light-primary'}
onClick={() => setDarkMode(!darkMode)}
>
{darkMode ? <BiSun size="1.7rem" /> : <BiMoon size="1.7rem" />}
</Nav.Link>
<Link
to="/cart"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{totalItems}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}> Cart</span>
</Link>
<Link
to="/wishlist"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{count.length}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}> Wishlist</span>
</Link>
{
isAuthenticated ? (
<>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log Out
</button>
</>
) : (
<
<details>
<summary>英文:</summary>
i have wishlist. When i adding items to my wishlist, i am adding items to my localStorage. And i need to show how many items i added to my wishlist.
i dont know how to render header (automatically) when changes value in (localStorage).
When i add items to wishlist it shows in span tag, everything good but in console i am getting: Warning: Maximum update depth exceeded.
Can someone help please?
Everything is on header component(page)
Header Page:
import React, { useContext, useState, useEffect } from 'react';
import { Container, Navbar, Nav } from 'react-bootstrap';
import { ThemeContext } from '../GlobalComponents/ThemeProvider';
import { BiSun, BiMoon, BiCart } from 'react-icons/bi';
import { VscAccount } from 'react-icons/vsc';
import { Link } from "@reach/router";
import { useCart } from "react-use-cart";
import { useAuth0 } from "@auth0/auth0-react";
const Header = () => {
const { theme, setThemeMode } = useContext(ThemeContext);
const [darkMode, setDarkMode] = useState(theme);
const { loginWithRedirect, logout, isAuthenticated, user, isLoading } = useAuth0();
const [count, setCount] = useState((JSON.parse(localStorage.getItem("liked"))));
const cou = () => {
let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
if (oldData.length === count.length) {
setCount((JSON.parse(localStorage.getItem("liked"))))
} else {
setCount((JSON.parse(localStorage.getItem("liked"))))
}
};
useEffect(() => {
let oldData = JSON.parse(localStorage.getItem('liked') || "[]")
if (oldData.length === count.length) {
setCount((JSON.parse(localStorage.getItem("liked"))))
} else {
setCount((JSON.parse(localStorage.getItem("liked"))))
}
}, [count]);
useEffect(() => {
setThemeMode(darkMode);
console.log(darkMode)
}, [darkMode]);
const {
isEmpty,
totalItems,
} = useCart();
if (isLoading) {
return (
<Navbar collapseOnSelect expand="md"
variant={darkMode ? 'dark' : 'light'}
className={darkMode ? 'bg-light-black border-bottom' : 'bg-light border-bottom'}
style={{ width: '100%', position: 'fixed', zIndex: 100 }}
>
<Container>
<Link to="/">
<Navbar.Brand className={darkMode ? 'text-dark-primary' : 'text-light-primary'}>
<img src='https://i.ibb.co/7kZrn4H/33342.png' width={200} />
</Navbar.Brand>
</Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ms-auto">
<div className='load'><div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div></div>
<Nav.Link
className={darkMode ? 'text-dark-primary' : 'text-light-primary'}
onClick={() => setDarkMode(!darkMode)}
>
{darkMode ? <BiSun size="1.7rem" /> : <BiMoon size="1.7rem" />}
</Nav.Link>
<Link
to="/cart"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{totalItems}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}>&nbsp;Cart</span>
</Link>
<Link
to="/wishlist"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}></span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}>&nbsp;Wishlist</span>
</Link>
{
isAuthenticated ? (
<>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log Out
</button>
</>
) : (
<>
<button onClick={() => loginWithRedirect()} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log in
</button>
</>
)
}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
return (
<Navbar collapseOnSelect expand="md"
variant={darkMode ? 'dark' : 'light'}
className={darkMode ? 'bg-light-black border-bottom' : 'bg-light border-bottom'}
style={{ width: '100%', position: 'fixed', zIndex: 100 }}
>
{/* <button onClick={()=>cou()}>Ref</button> */}
<Container>
<Link to="/">
<Navbar.Brand className={darkMode ? 'text-dark-primary' : 'text-light-primary'}>
<img src='https://i.ibb.co/7kZrn4H/33342.png' width={200} />
</Navbar.Brand>
</Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ms-auto">
{
isAuthenticated && (
<>
<p className={`d-flex align-items-center user-name ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>{user.email}</p>
</>
)
}
<Nav.Link
className={darkMode ? 'text-dark-primary' : 'text-light-primary'}
onClick={() => setDarkMode(!darkMode)}
>
{darkMode ? <BiSun size="1.7rem" /> : <BiMoon size="1.7rem" />}
</Nav.Link>
<Link
to="/cart"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{totalItems}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}>&nbsp;Cart</span>
</Link>
<Link
to="/wishlist"
className={`${darkMode ? 'text-dark-primary' : 'text-light-primary'} d-flex align-items-center`}
>
<BiCart size="2rem" />
{!isEmpty && <span style={{ position: 'relative', left: '-21px', top: '-18px' }}>{count.length}</span>}
<span style={{ marginLeft: !isEmpty ? '-13px' : 0 }}>&nbsp;Wishlist</span>
</Link>
{
isAuthenticated ? (
<>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log Out
</button>
</>
) : (
<>
<button onClick={() => loginWithRedirect()} className={`login-btn ${darkMode ? 'text-dark-primary' : 'text-light-primary'}`}>
Log in
</button>
</>
)
}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
};
export default Header;
ProductCard page:
import React, { useState } from 'react';
import { Button, Card } from 'react-bootstrap';
import { useThemeHook } from '../GlobalComponents/ThemeProvider';
import { useCart } from 'react-use-cart';
import { BsCartPlus } from 'react-icons/bs';
import { Link } from "@reach/router";
import { useInView } from 'react-intersection-observer';
const ProductCard = (props) => {
// const [state,setState]=useState({
// favourites:[]
// });
const [favourites, setFavourites] = useState([]);
let { image, price, title, id } = props.data;
const [theme] = useThemeHook();
const { addItem } = useCart();
const { ref: headerAni, inView: headerAniVisible } = useInView();
const addToCart = () => {
addItem(props.data);
}
const handleFavourites = (likedItem) => {
let oldData = JSON.parse(localStorage.getItem('liked')) ?? []
if (favourites.includes(likedItem.id)) {
oldData = oldData.filter((m) => m.id !== likedItem.id)
console.log("if", oldData)
} else {
oldData.push(likedItem)
console.log("else", oldData)
}
localStorage.setItem("liked", JSON.stringify(oldData));
console.log(oldData);
handleFavouritesState();
};
const handleFavouritesState = () => {
let oldData = JSON.parse(localStorage.getItem("liked")) ?? []
let temp = oldData.map((likedItem) => likedItem.id);
setFavourites([...temp])
console.log("son", oldData)
};
return (
<>
<Card
style={{ width: '18rem', height: 'auto' }}
className={`${theme ? 'bg-light-black text-light' : 'bg-lihgt text-black'} text-center p-0 overflow-hidden shadow mx-auto mb-4`}
ref={headerAni}
>
<Link to={`/product-details/${id}`}>
<div style={{
background: 'white', height: '15rem', overflow: 'hidden', display: 'flex',
justifyContent: 'center', alignItems: 'center', marginBottom: 'inherit'
}}>
<div style={{ width: '9rem' }}>
<Card.Img variant="top" src={image} className="img-fluid" data-aos-easing="ease-out-cubic"
data-aos-duration="3000" data-aos={`${headerAniVisible ? "" : "zoom-out"}`} />
</div>
</div>
</Link>
<Card.Body>
<Card.Title style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
{title}
</Card.Title>
<Card.Title>
$ <del><span className="">{price * 2}</span></del>
</Card.Title>
<Card.Title>
$ <span className="h3">{price}</span>
</Card.Title>
<Button
onClick={() => addToCart()}
className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex align-item-center m-auto border-0`}
>
<BsCartPlus size="1.8rem" />
Add to cart
</Button>
<Button
onClick={() => handleFavourites(props.data)}
className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex align-item-center m-auto border-0`}
>
<BsCartPlus size="1.8rem" />
Add to Favourites
</Button>
</Card.Body>
</Card>
</>
);
};
export default ProductCard;
</details>
# 答案1
**得分**: 1
以下是您要翻译的内容:
正如评论中提到的那样。您收到警告是因为您存在无限循环,因为您正在监听并更新相同的状态。
以下是您可以尝试的方法。当您点击“添加到愿望清单”时,只需更新您的计数状态。将新项目附加到存储在计数状态中的现有愿望清单。然后,useEffect 将负责将愿望清单添加/同步到本地存储。
```jsx
export default function App() {
// 初始状态将从本地存储中获取愿望清单项目并设置在状态中
const [count, setCount] = useState(JSON.parse(localStorage.getItem("liked")) || []);
// 这是您的添加到愿望清单函数。您可以创建类似的函数来从愿望清单中删除项目。在那种情况下,您只需要过滤计数状态。
const addToWishlist = (item) => {
setCount(prev => [...prev, item]);
};
// 每当状态更改时,这将更新您的本地存储。
useEffect(() => {
localStorage.setItem("liked", JSON.stringify(count));
}, [count]);
return (
<div>
<h1>愿望清单</h1>
<h2>{count.length}</h2>
<button onClick={() => addToWishlist({id: 1, name: 'test'})}>添加到愿望清单</button>
</div>
);
}
希望对您有所帮助。如果您需要进一步的帮助,请告诉我。
英文:
As mentioned in the comments. You are getting warning because you are having infinite loop as you are listening to and updating the same state.
Here is what you can try. When you click Add to wishlist just update your count state. Append new item to your existing wishlist stored in the count state. And then the useEffect will take care of adding/synching wishlist to the localstorage.
export default function App() {
// Initial state will pull wishlist items from localstorage and set it in state
const [count, setCount] = useState(JSON.parse(localStorage.getItem("liked")) || []);
// This is your add to wishlist function. You can create similar function to remove item from wishlist. In that case you just need to filter the count state.
const addToWishlist = (item) => {
setCount(prev => [...prev, item]);
};
// This will update your localstorage whenever state changes.
useEffect(() => {
localStorage.setItem("liked", JSON.stringify(count));
}, [count]);
return (
<div>
<h1>Wishlist</h1>
<h2>{count.length}</h2>
<button onClick={() => addToWishlist({id: 1, name: 'test'})}>Add to Wishlist</button>
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论