关于reactuseState更新异步问题.docxVIP

  • 0
  • 0
  • 约2.58千字
  • 约 5页
  • 2025-05-18 发布于四川
  • 举报

关于reactuseState更新异步问题

目录reactuseState更新异步记useState异步更新小坑问题点

reactuseState更新异步

当我们使用react中useState这个hook时候,如下

const[page,setPage]=useState(1);

consthandlerClick=(e)={

???setPage(e.current);

???console.log(page);

}

当我打印page时候,此时page还是1,因为useState的更新是异步的,这和react的机制有关,要解决这个可以这样做

1.使用useState的返回值

?setPage(e.current);

????setPage(prevFoo={

??????console.log(page===========,prevFoo);//page===========2

??????returnprevFoo;

?});

2.自定义hook(第一种方式)

??constuseSyncCallback=callback={

????const[proxyState,setProxyState]=useState({current:

文档评论(0)

1亿VIP精品文档

相关文档