debugging 如何将所有值存储在本地存储中,以便每次单击后都不会重置?

58wvjzkj  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(113)

我试图将所有的likedUserIdsdislikedUserIds存储在本地存储器中,但是由于某种原因,它甚至没有命中if()语句。likedPhotoUserId函数参数确实有一个值,那么为什么它没有命中第一个if()
任何反馈将不胜感激!

const handleLikesBasedOnUserId = (likedPhotoUserId) => {
    console.log(likedPhotoUserId); // value is present

        // dislike

        if(likedPhotoUserId) {
            // if the user id exists
            if(localStorage.getItem('dislikedUserIds')) {
                console.log("inside if");
                // split the existing values into an array
                let vals = localStorage.getItem('dislikedUserIds').split(',');

                // if the value has not already been added
                if (!vals.includes(likedPhotoUserId)) {

                    // add the value to the array
                    vals.push(likedPhotoUserId);

                    // sort the array
                    vals.sort();

                    // join the values into a delimeted string and store it
                    localStorage.setItem('dislikedUserIds', vals.join(','));
                } else {
                    console.log("inside else");
                    // the key doesn't exist yet, add it and the new value
                    localStorage.setItem('dislikedUserIds', likedPhotoUserId);
                }
            }
        } else {

        // like

        if(likedPhotoUserId) {
            // if the user id exists
            if(localStorage.getItem('likedUserIds')) {
                console.log("inside if");
                // split the existing values into an array
                let vals = localStorage.getItem('likedUserIds').split(',');

                // if the value has not already been added
                if (!vals.includes(likedPhotoUserId)) {

                    // add the value to the array
                    vals.push(likedPhotoUserId);

                    // sort the array
                    vals.sort();

                    // join the values into a delimeted string and store it
                    localStorage.setItem('likedUserIds', vals.join(','));
                } else {
                    console.log("inside else");
                    // the key doesn't exist yet, add it and the new value
                    localStorage.setItem('likedUserIds', likedPhotoUserId);
                }
            }
        }

    }

};
vhmi4jdf

vhmi4jdf1#

如果我没有误解的话,你可以用一种更易读的方式来做这件事:

function likeOrDislike(likedPhotoId) {
    // Get value or define empty
    const likedStored = localStorage.getItem("likedIds") || "[]";
    // Convert string into array
    let likedArray = JSON.parse(likedStored);
    
    // Check if exists or not
    if (likedArray.includes(likedPhotoId)) {
        // Remove from array
        likedArray = likedArray.filter(
            (photo) => photo !== likedPhotoId
        );
    } else {
        // Add to Array
        likedArray.push(likedPhotoId);
    }
    // Convert to string to store in localStorage
    const stringLiked = JSON.stringify(likedArray);
    localStorage.setItem("likedIds", stringLiked);
}
t3psigkw

t3psigkw2#

我很难理解你的代码中的逻辑,但我很确定这能满足你的用例。你的代码从来没有达到第一个条件的问题特别令人困惑,因为在我的测试中没有发生过这种情况。

// when repeating strings in code, it's useful to set them
// as variables so your autocomplete and linter can help you out
const likedStorageKey = 'likedUserIds'
const dislikedStorageKey = 'dislikedUserIds'

// using JSON is a little easier than manually building and splitting the list
const storageListOrDefault = (key) =>
  JSON.parse(localStorage.getItem(key)) || []

const setStorageItem = (key, list) =>
  localStorage.setItem(key, JSON.stringify(list))

// if an item is in the list, remove it
const removeFromOppositeList = (storageKey, toRemove) => {
  const vals = storageListOrDefault(storageKey)
  setStorageItem(storageKey, vals.filter((id) => id !== toRemove))
}

const toggleInList = (storageKey, toAdd) => {
  const vals = storageListOrDefault(storageKey)
  // here we filter the old list, assuming you want your like/dislike
  // buttons to have a 'neutral' state.
  // if the array already includes the item and you're toggling to a neutral
  // state, we remove the id
  // if the list doesn't include the id, we concat the id to the array, and sort
  const newList = vals.includes(toAdd)
    ? vals.filter((x) => x === toAdd)
    : [...vals, toAdd].sort()
  setStorageItem(storageKey, newList)
}

// onClick functions for your like and dislike buttons
const handleLike = (id) => {
  if (id) {
    removeFromOppositeList(dislikedStorageKey, id)
    toggleInList(likedStorageKey, id)
  }
}

const handleDislike = (id) => {
  if (id) {
    removeFromOppositeList(likedStorageKey, id)
    toggleInList(dislikedStorageKey, id)
  }
}

性能说明:所有这些都不是特别有效,但是如果您担心性能,我建议您使用一个专为这种具有持久性的状态管理而设计的库。

相关问题