在单个函数中两次设置状态-ReactJS [英] Set state twice in a single function - ReactJS

查看:42
本文介绍了在单个函数中两次设置状态-ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置状态两次的函数,但是-第二个 setState 必须在500ms之后发生,因为第一个 setState 发生了(动画目的).

I have a function that sets state twice, however - the second setState has to occur after 500ms since first setState has occured (animation purposes).

代码如下:

const showAnimation = () => {
   this.setState({ hidden: false });

   setTimeout(() => {
      this.setState({ hidden: true });
   }, 500);
};

但是-如果我这样做,React将以某种方式将这两个 setState 合并为一个,而我的动画无法正常工作.

However - if I do it this way, React somehow merges these two setState's into one and my animation doesn't work as expected.

但是,如果我使用hack:

But, if I use a hack:

const showAnimation = () => {
   setTimeout(() => {
      this.setState({ hidden: false });
   }, 0);  // ------------------------------> timeout 0

   setTimeout(() => {
      this.setState({ hidden: true });
   }, 500);
};

它按预期工作.但是,我还是不太喜欢它,我担心这可能是一种黑客.对于这种情况有更好的解决方案吗?谢谢:)

It works as expected. But still, I don't really like it and Im afraid that it may be some kind of a hack. Is there any better solution for such case? Thanks :)

推荐答案

由于 setState 在React中是异步的,您可能不会立即获得更新状态,但是 setState 会为您提供 setState 函数中的> prevState 参数可获取上次更新的状态,这样您就不会合并状态

As setState are async in React you might not get updated state immediately but setState gives you prevState param in setState function to get last updated state so you won't merge state

语法因您而异

this.setState((prevState) => { hidden: false }, () => {
      setTimeout(() => {
        this.setState({ hidden: !prevState.hidden });
      }, 500);
    });

只需使用 prevState

如果我了解您的问题,此方法应该可以正常运行
请让我知道是否需要进一步说明

If I understand your problem correct this should work fine
Please let me know if more clarification required

这篇关于在单个函数中两次设置状态-ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆