【问题标题】:How to check if the array has received a new value?如何检查数组是否收到新值?
【发布时间】:2022-11-23 18:12:47
【问题描述】:

我正在尝试创建一个自定义通知计数器,它显示未读通知的数量。 我从后端接收通知内容作为数组。 我的想法是获取第一个值,检查先前的长度是否与当前长度不同,然后将此计数器加到 +1(或更多)。

  useEffect(() => {
    axios
      .get(USER_API)
      .then((response) => {
        setNotificationList(response.data.data);
      })
      .catch((error) => console.log('error from getNotifications', error));
    });

我怎样才能让它发挥作用?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在设置状态下使用回调函数

      setNotificationList((prev) => {
         if(prev?.length === response.data.data.length) return prev 
         return response.data.data
       } );
    

    【讨论】:

    • prev.length 未定义
    • 使用prev?.length
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2011-01-27
    • 2021-10-08
    • 2012-01-10
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多