简体   繁体   English

在 NextJS 中使用 async 和 Cookies.get 的 useEffect

[英]useEffect with async and Cookies.get in NextJS

I'm trying to get cookie data in use effect and then use that data, my component looks like this..我正在尝试获取使用效果的 cookie 数据,然后使用该数据,我的组件看起来像这样..

const Favourites = (props) => {
  const [isClick, setClick] = useState(false);

  const activityId = props.activityId

  useEffect(() => {
    const favourites = Cookies.get('favourites')
    if (favourites[activityId] === true) {
      setClick(true)
    }
  })

  return (
    <>
      <div className="heart">
        <Heart isClick={isClick} onClick={() => setClick(!isClick)} />
      </div>

    </>
  );
}

this is what I get when I console.log(Cookies.get('favourites')) -这就是我在 console.log(Cookies.get('favourites')) 时得到的 -

{"5edf47240dcb4713d3942e1b":true,"5edf47240dcb4713d3942e2b":true,"5fa10bd8f70458050ffe68af":true}

changing改变

const favourites = Cookies.get('favourites')

to

const favourites = {"5edf47240dcb4713d3942e1b":true,"5edf47240dcb4713d3942e2b":true,"5fa10bd8f70458050ffe68af":true}

produces the desired effect.产生想要的效果。

favourites is an array of activityID's stored in localstorage using js-cookie.收藏夹是使用 js-cookie 存储在本地存储中的活动 ID 数组。 it's basically a list of the users favourite activities, if they like the activity and click the heart button then the activityID is stored as the key and the value is set to true它基本上是用户最喜欢的活动的列表,如果他们喜欢该活动并单击心形按钮,则将 activityID 存储为键并将值设置为 true

the above doesn't work, setClick isn't being set to true if the activityId is true in the favourites array.以上不起作用,如果在收藏夹数组中 activityId 为 true,则 setClick 不会设置为 true。 If I console.log(Cookies.get('favourites')) and copy the result into const favourites then it does work如果我 console.log(Cookies.get('favourites')) 并将结果复制到 const favorites 那么它确实有效

From your edit, it looks like what console.log is showing is actually a string .从您的编辑看来, console.log显示的实际上是一个string So, doing a JSON.decode on what Cookies.get is returning should do the trick:因此,对Cookies.get返回的内容执行JSON.decode应该可以解决问题:

const favourites = JSON.decode(Cookies.get('favourites'));

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

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