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

Modify React state variable after specified time

我想在指定时间后从数组中删除一些条目。 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
}

您的代码没问题!问题是你在哪里记录它。

所有状态更新都是异步的。使用钩子,更新后的值仅在下一个 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);