ReactJS中的if else返回false。

huangapple go评论115阅读模式
英文:

ReactJS if else gives false

问题

I have reviewed the provided code. If you have any specific questions or need assistance with a particular part of the code, please feel free to ask.

英文:

i have button (for add item to localStorage) when i click "Add to favourites" adding item to localStorage and when i click again it deleting this item from localStorage, everything fine. But when i refresh page and click button it only adding, i mean refreshing clicking, refreshing clicking and it only adding it must be delete because i already added 1 time. And when i click two times without refreshing it deleting 1 item which i want 2-3 times(how many time i added with refresh). if gives me false every time with refresh, without refresh (clicking 2 times) then it gives me true. i think something wrong with if. Can someone help me please?

  1. import React, { useState } from 'react';
  2. import { Button, Card } from 'react-bootstrap';
  3. import { useThemeHook } from '../GlobalComponents/ThemeProvider';
  4. import { useCart } from 'react-use-cart';
  5. import { BsCartPlus } from 'react-icons/bs';
  6. import { Link } from "@reach/router";
  7. import { useInView } from 'react-intersection-observer';
  8. import { MainContext, useContext } from '../context';
  9. const ProductCard = (props) => {
  10. // const [state,setState]=useState({
  11. // favourites:[]
  12. // });
  13. const { favourites, setFavourites} = useContext(MainContext);
  14. let { image, price, title, id } = props.data;
  15. const [theme] = useThemeHook();
  16. const { addItem } = useCart();
  17. const { ref: headerAni, inView: headerAniVisible } = useInView();
  18. const addToCart = () => {
  19. addItem(props.data);
  20. }
  21. const handleFavourites = (likedItem) => {
  22. let oldData = JSON.parse(localStorage.getItem('liked')) ?? []
  23. if (favourites.includes(likedItem.id)) {
  24. oldData = oldData.filter((m) => m.id !== likedItem.id)
  25. console.log("if", oldData)
  26. } else {
  27. oldData.push(likedItem)
  28. console.log("else", oldData)
  29. }
  30. localStorage.setItem("liked", JSON.stringify(oldData));
  31. console.log(oldData);
  32. handleFavouritesState();
  33. };
  34. const handleFavouritesState = () => {
  35. let oldData = JSON.parse(localStorage.getItem("liked")) ?? []
  36. let temp = oldData.map((likedItem) => likedItem.id);
  37. setFavourites([...temp])
  38. console.log("son", oldData)
  39. };
  40. return (
  41. <>
  42. <Card
  43. style={{ width: '18rem', height: 'auto' }}
  44. className={`${theme ? 'bg-light-black text-light' : 'bg-lihgt text-black'} text-center p-0 overflow-hidden shadow mx-auto mb-4`}
  45. ref={headerAni}
  46. >
  47. <Link to={`/product-details/${id}`}>
  48. <div style={{
  49. background: 'white', height: '15rem', overflow: 'hidden', display: 'flex',
  50. justifyContent: 'center', alignItems: 'center', marginBottom: 'inherit'
  51. }}>
  52. <div style={{ width: '9rem' }}>
  53. <Card.Img variant="top" src={image} className="img-fluid" data-aos-easing="ease-out-cubic"
  54. data-aos-duration="3000" data-aos={`${headerAniVisible ? "" : "zoom-out"}`} />
  55. </div>
  56. </div>
  57. </Link>
  58. <Card.Body>
  59. <Card.Title style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
  60. {title}
  61. </Card.Title>
  62. <Card.Title>
  63. $ <del><span className="">{price * 2}</span></del>
  64. </Card.Title>
  65. <Card.Title>
  66. $ <span className="h3">{price}</span>
  67. </Card.Title>
  68. <Button
  69. onClick={() => addToCart()}
  70. className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex align-item-center m-auto border-0`}
  71. >
  72. <BsCartPlus size="1.8rem" />
  73. Add to cart
  74. </Button>
  75. <Button
  76. onClick={() => handleFavourites(props.data)}
  77. className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex align-item-center m-auto border-0`}
  78. >
  79. <BsCartPlus size="1.8rem" />
  80. Add to Favourites
  81. </Button>
  82. </Card.Body>
  83. </Card>
  84. </>
  85. );
  86. };
  87. export default ProductCard;

i get data from home component with props if it will be help you

  1. import { useRef } from 'react';
  2. import React, { useEffect, useState } from 'react';
  3. import { Container, Row, Col, InputGroup, FormControl } from 'react-bootstrap';
  4. import { useThemeHook } from '../GlobalComponents/ThemeProvider';
  5. import { BiSearch } from 'react-icons/bi';
  6. import SearchFilter from 'react-filter-search';
  7. import ProductCard from '../components/ProductCard';
  8. import Carousel from 'react-bootstrap/Carousel';
  9. import ScrollAnimation from 'react-animate-on-scroll';
  10. import { useInView } from 'react-intersection-observer';
  11. const Home = () => {
  12. const [theme] = useThemeHook();
  13. const [searchInput, setSearchInput] = useState('');
  14. const [productData, setProductData] = useState([]);
  15. const { ref: myRef, inView: myElementIsVisible } = useInView();
  16. const { ref: rocketRef, inView: rocketIsVisible } = useInView();
  17. const { ref: bannerOne, inView: bannerOneVisible } = useInView();
  18. const { ref: headerAni, inView: headerAniVisible } = useInView();
  19. async function getResponse() {
  20. const res = await fetch('https://fakestoreapi.com/products')
  21. .then(res => res.json());
  22. setProductData(await res);
  23. }
  24. useEffect(() => {
  25. getResponse();
  26. }, []);
  27. const [sortState, setSortState] = useState("none");
  28. const sortMethods = {
  29. none: { method: (a, b) => null },
  30. ascending: { method: (a, b) => (a.price - b.price) },
  31. descending: { method: (a, b) => (a.title > b.title ? 1 : -1) },
  32. };
  33. return (
  34. <>
  35. <Carousel fade className='padd-1' data-aos-easing="ease-out-cubic"
  36. data-aos-duration="2000" data-aos={`${headerAniVisible ? "" : "fade-up"}`}>
  37. <Carousel.Item ref={headerAni}>
  38. <img
  39. className="d-block w-100"
  40. src="https://i.ibb.co/vwB9BV2/Untitled-design-33.png"
  41. alt="First slide"
  42. />
  43. <Carousel.Caption className='wid-300 pad-top' >
  44. <h3>24/7 Texniki dəstək!</h3>
  45. <p>
  46. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. I
  47. </p>
  48. <a href='#' className='button'>More info</a>
  49. </Carousel.Caption>
  50. </Carousel.Item>
  51. <Carousel.Item ref={headerAni}>
  52. <img
  53. className="d-block w-100"
  54. src="https://i.ibb.co/PwrBm7q/Untitled-design-32.png"
  55. alt="Second slide"
  56. />
  57. <Carousel.Caption className='wid-300 pad-top' >
  58. <h3>What is Lorem Ipsum?</h3>
  59. <p>
  60. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. I
  61. </p>
  62. <a href='#' className='button'>More info</a>
  63. </Carousel.Caption>
  64. </Carousel.Item>
  65. <Carousel.Item ref={headerAni}>
  66. <img
  67. className="d-block w-100"
  68. src="https://i.ibb.co/HYKM6z4/Untitled-design-34.png"
  69. alt="Third slide"
  70. />
  71. <Carousel.Caption className='wid-300 pad-top' >
  72. <h3>What is Lorem Ipsum?</h3>
  73. <p>
  74. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. I
  75. </p>
  76. <a href='#' className='button'>More info</a>
  77. </Carousel.Caption>
  78. </Carousel.Item>
  79. </Carousel>
  80. <section className='home-wrapper-1 py-5' >
  81. <div className='container-xxl padd' >
  82. <div className='row' >
  83. <div className='col-6'>
  84. <div className='main-banner position-relative' ref={rocketRef}>
  85. <img
  86. src='https://i.ibb.co/PZtF0RM/main-banner-1.jpg'
  87. className='img-fluid rounded-3'
  88. alt='banner'
  89. data-aos-easing="ease-out-cubic"
  90. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-right"}`}
  91. />
  92. <div className='main-banner-content position-absolute' data-aos-easing="ease-out-cubic"
  93. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-right"}`}>
  94. <h4>SUPERCHARGED FOR PODS</h4>
  95. <h5>iPad S13+ Pro</h5>
  96. <p>From $999.00 or $41.62/mo.</p>
  97. <a href='#' className='button'>BUY NOW</a>
  98. </div>
  99. </div>
  100. </div>
  101. <div className='col-6'>
  102. <div className='d-flex flex-wrap gap justify-content-between align-items-center'>
  103. <div className='small-banner position-relative' ref={rocketRef}>
  104. <img
  105. src='https://i.ibb.co/HrZjrXC/catbanner-01.jpg'
  106. className='img-fluid rounded-3'
  107. alt='banner'
  108. data-aos-easing="ease-out-cubic"
  109. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-down"}`}
  110. />
  111. <div className='small-banner-content position-absolute' data-aos-easing="ease-out-cubic"
  112. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-down"}`}>
  113. <h4>Best Sale</h4>
  114. <h5>iPad S13+ Pro</h5>
  115. <p>From $999.00 <br /> or $41.62/mo.</p>
  116. </div>
  117. </div>
  118. <div className='small-banner position-relative' ref={rocketRef}>
  119. <img
  120. src='https://i.ibb.co/34Zk6Jv/catbanner-02.jpg'
  121. className='img-fluid rounded-3'
  122. alt='banner'
  123. data-aos-easing="ease-out-cubic"
  124. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-down"}`}
  125. />
  126. <div className='small-banner-content position-absolute' data-aos-easing="ease-out-cubic"
  127. data-aos-duration="2000" data-aos={`${rocketIsVisible ? "" : "fade-down"}`}>
  128. <h4>NEW ARRIVAL</h4>
  129. <h5>Buy IPad Air</h5>
  130. <p>From $999.00 <br /> or $41.62/mo.</p>
  131. </div>
  132. </div>
  133. <div className='small-banner position-relative' ref={bannerOne}>
  134. <img
  135. src='https://i.ibb.co/5F9BZfw/catbanner-03.jpg'
  136. className='img-fluid rounded-3'
  137. alt='banner'
  138. data-aos-easing="ease-out-cubic"
  139. data-aos-duration="2000" data-aos={`${bannerOneVisible ? "" : "fade-up"}`}
  140. />
  141. <div className='small-banner-content position-absolute' data-aos-easing="ease-out-cubic"
  142. data-aos-duration="2000" data-aos={`${bannerOneVisible ? "" : "fade-up"}`}>
  143. <h4>NEW ARRIVAL</h4>
  144. <h5>Buy IPad Air</h5>
  145. <p>From $999.00 <br /> or $41.62/mo.</p>
  146. </div>
  147. </div>
  148. <div className='small-banner position-relative' ref={bannerOne}>
  149. <img
  150. src='https://i.ibb.co/pynHmdz/catbanner-04.jpg'
  151. className='img-fluid rounded-3'
  152. alt='banner'
  153. data-aos-easing="ease-out-cubic"
  154. data-aos-duration="2000" data-aos={`${bannerOneVisible ? "" : "fade-up"}`}
  155. />
  156. <div className='small-banner-content position-absolute' data-aos-easing="ease-out-cubic"
  157. data-aos-duration="2000" data-aos={`${bannerOneVisible ? "" : "fade-up"}`}>
  158. <h4>NEW ARRIVAL</h4>
  159. <h5>Buy IPad Air</h5>
  160. <p>From $999.00 <br /> or $41.62/mo.</p>
  161. </div>
  162. </div>
  163. </div>
  164. </div>
  165. </div>
  166. </div>
  167. </section>
  168. <Container className="py-4">
  169. <Row className="justify-content-center">
  170. <Col xs={10} md={7} lg={6} xl={4} className="mb-3 mx-auto text-center">
  171. <h1 className={theme ? 'text-light my-5' : 'text-black my-5'}>Search products</h1>
  172. <InputGroup className="mb-3">
  173. <InputGroup.Text className={theme ? 'bg-black text-dark-primary' : 'bg-light text-light-primary'}>
  174. <BiSearch size="2rem" />
  175. </InputGroup.Text>
  176. <FormControl
  177. placeholder="Search"
  178. value={searchInput}
  179. onChange={(e) => setSearchInput(e.target.value)}
  180. className={theme ? 'bg-light-black text-light' : 'bg-light text-black'}
  181. />
  182. </InputGroup>
  183. </Col>
  184. <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }} className='mb-3'>
  185. <select style={{ width: '100px' }} defaultValue={'none'} onChange={(e) => setSortState(e.target.value)}>
  186. <option value="none">None</option>
  187. <option value="ascending">Price</option>
  188. <option value="descending">A-Z</option>
  189. </select>
  190. </div>
  191. <SearchFilter
  192. value={searchInput}
  193. data={productData}
  194. renderResults={results => (
  195. <Row className="justify-content-center">
  196. {results?.sort(sortMethods[sortState].method).map((item, i) => (
  197. <ProductCard data={item} key={i} />
  198. ))}
  199. </Row>
  200. )}
  201. />
  202. </Row>
  203. </Container>
  204. </>
  205. );
  206. };
  207. export default Home;

答案1

得分: 0

It seems that the issue is with the logic of the "handleFavourites" function.

  1. const handleFavourites = (likedItem) => {
  2. let oldData = JSON.parse(localStorage.getItem('liked')) ?? [];
  3. if (favourites.includes(likedItem.id)) {
  4. oldData = oldData.filter((m) => m.id !== likedItem.id);
  5. console.log("if", oldData);
  6. } else {
  7. oldData.push(likedItem);
  8. console.log("else", oldData);
  9. }
  10. localStorage.setItem("liked", JSON.stringify(oldData));
  11. console.log(oldData);
  12. handleFavouritesState();
  13. };

Checking if the oldData retrieved from the localStorage includes the id of the likedItem.

  1. if (oldData.some((item) => item.id === likedItem.id)) {
  2. oldData = oldData.filter((m) => m.id !== likedItem.id);
  3. console.log("if", oldData);
  4. } else {
  5. oldData.push(likedItem);
  6. console.log("else", oldData);
  7. }
英文:

It seems that the issue is with the logic of the "handleFavourites"

  1. const handleFavourites = (likedItem) => {
  2. let oldData = JSON.parse(localStorage.getItem('liked')) ?? []
  3. if (favourites.includes(likedItem.id)) {
  4. oldData = oldData.filter((m) => m.id !== likedItem.id)
  5. console.log("if", oldData)
  6. } else {
  7. oldData.push(likedItem)
  8. console.log("else", oldData)
  9. }
  10. localStorage.setItem("liked", JSON.stringify(oldData));
  11. console.log(oldData);
  12. handleFavouritesState();

};

checking if the oldData retrieved from the localStorage includes the id of the likedItem

  1. if (oldData.some((item) => item.id === likedItem.id)) {
  2. oldData = oldData.filter((m) => m.id !== likedItem.id)
  3. console.log("if", oldData)
  4. } else {
  5. oldData.push(likedItem)
  6. console.log("else", oldData)

}

huangapple
  • 本文由 发表于 2023年4月13日 19:42:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定