简体   繁体   English

React.js - 更改所有书签状态而不是特定状态

[英]React.js - Changing all bookmark states instead specific one

I am creating app for bookmarking marvel characters (heroes), so when I click on specific bookmark icon it should change into filled bookmark icon and vice-versa.我正在创建用于为奇迹人物(英雄)添加书签的应用程序,因此当我单击特定的书签图标时,它应该变为填充的书签图标,反之亦然。 Unfortunately when I click on single one all icons change.不幸的是,当我单击一个时,所有图标都会更改。 I guess the problem is in the state.我想问题出在 state 上。 Please help!请帮忙!

As a prop I am receiving all data about characters (image, name) Here is the code:作为道具,我正在接收有关字符(图像,名称)的所有数据这是代码:

import React, { useState, useEffect } from "react";
import "./CharactersList.css";
import { RiBookmarkLine } from "react-icons/ri";
import { RiBookmarkFill } from "react-icons/ri";

const CharactersList = (props) => {
  const [isLiked, setisLiked] = useState(false);
  const [toggle, setToggle] = useState(false);
  const [favourites, setFavourites] = useState([]);

  useEffect(() => {
    const bookMarkedData = JSON.parse(
      localStorage.getItem("react-bookmarked-characters")
    );
    if (bookMarkedData) {
      setFavourites(bookMarkedData);
    }
  }, []);

  const saveToLocalStorage = (data) => {
    localStorage.setItem("react-bookmarked-characters", JSON.stringify(data));
  };

  const handleBookmarking = (character) => {
    if (toggle === true) {
      const newBookmarkedList = [...favourites, character];
      setFavourites(newBookmarkedList);
      saveToLocalStorage(newBookmarkedList);
      setisLiked(true);
    } else {
      const newBookmarkedList = favourites.filter(
        (favourites) => favourites.id !== character.id
      );
      setFavourites(newBookmarkedList);
      saveToLocalStorage(newBookmarkedList);
      setisLiked(false);
    }
  };

  const toggleLike = () => {
    setisLiked(!isLiked);
    Bookmarked(isLiked);
  };

  const Bookmarked = () => {
    return isLiked ? <RiBookmarkFill /> : <RiBookmarkLine />;
  };

  return (
    <>
      {props.characters.map((character, index) => (
        <div className="card-container" key={index}>
          <img
            src={`${character.thumbnail.path}/standard_fantastic.${character.thumbnail.extension}`}
            alt="character"
            className="image"
          />
          <div className="info-container">
            <p className="name">{character.name}</p>
            <div
              className="icon"
              onClick={() => {
                setToggle(!toggle);
                handleBookmarking(character);
              }}
            >
              <Bookmarked />
            </div>
          </div>
        </div>
      ))}
    </>
  );
};

export default CharactersList;

Problem is in the state you are right.问题出在 state 你是对的。 You are storing one boolean value for all your heroes.您正在为所有英雄存储一个 boolean 值。 You should change the state value to an array of ids instead of one boolean and in this array, you store ids of bookmarked characters.您应该将 state 值更改为一个 id 数组,而不是一个 boolean,并且在这个数组中,您存储书签字符的 id。 So your handleBookmarking function should be something like this:所以你的 handleBookmarking function 应该是这样的:

const handleBookmarking = (character) => {
   if (isLiked.includes(character.id)) {
      const newIsLiked = [...isLiked];
      newIsLiked.filter(id => id === character.id);
      setIsLiked(newIsLiked);
   } else {
      setIsLiked([...isLiked, character.id]);
   }
}

With this implementation, you no longer need toggle state.通过此实现,您不再需要切换 state。 If your character's id is in the array, it's bookmarked and if it's not, it's not bookmarked.如果你的角色的 id 在数组中,它会被添加到书签中,如果不是,则不会被添加到书签中。 If your character doesn't have an id, you can use name or any other prop that is unique.如果您的角色没有 id,您可以使用 name 或任何其他唯一的道具。 You will also have to change your BookMarked component implementation to something like this:您还必须将 BookMarked 组件实现更改为如下所示:

//implementation of BookMarked
const Bookmarked = ({id}) => {
   return isLiked.includes(id) ? <RiBookmarkFill /> : <RiBookmarkLine />;
};

And also change it in return statement:并在 return 语句中更改它:

//from this:
<Bookmarked />

//to this: 
<Bookmarked id={character.id} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM