在指定时间后修改React状态变量

时间:2019-11-22 13:40:31

标签: reactjs setinterval react-hooks

我想在指定的时间后从数组中删除一些条目。 notifications应该立即更改,但实际上它保持不变。有办法实现我的目标吗?

const Notifications = props => {
  const [notifications, setNotifications] = useState([
    { value: '123', time: Date.now() },
    { value: '456', time: Date.now() }
  ]);
  useEffect(() => {
    let interval = setInterval(() => {
      console.log(notifications);
      let time = Date.now();
      let array = notifications.filter(function(item) {
        return time < item.time + 0;
      });
      setNotifications(array);
    }, 500);
    return () => {
      clearInterval(interval);
    };
  }, []);

  return null
}

1 个答案:

答案 0 :(得分:3)

您的代码很好!问题是您在哪里记录它。

所有状态更新都是异步的。使用挂钩,仅在下一个render调用中,更新的值才会显示在组件的范围内。如果您不在效果范围内登录,则应该看到正确的值

const Notifications = props => {
  const [notifications, setNotifications] = useState([
    { value: '123', time: Date.now() },
    { value: '456', time: Date.now() }
  ]);
  useEffect(() => {
    let interval = setInterval(() => {
      let time = Date.now();
      let array = notifications.filter(function(item) {
        return time < item.time + 0;
      });
      setNotifications(array);
    }, 500);
    return () => {
      clearInterval(interval);
    };
  }, []);

  return null
}

console.log(notifications);