繁体   English   中英

在useEffect中有多个setState,如何避免重新渲染?

[英]more than one setState in useEffect, how to aviod re-render?

当我在useEffect中有多个setState时,如何避免重新渲染?

我想进行2个API调用并在useEffect中设置3个不同的状态(当组件确实挂载时),并且只有一个重新渲染

像这样的东西

useEffect(()=>{
   axios.get('http://localhost:81/api/myapi/')
   .then(res=>{
     setName(res.data['name']);
     setPrice(res.data['price']);
   })

   axios.get('http://localhost:81/api/mysecondapi/')
   .then(res=>{
     setColors(res.data['colors']);
   })
 },[]);

我只需要一整套渲染图。 我知道在每个setStates之后重新渲染是正确的,但是我怎样才能做到这一点呢? 将所有状态都放在一个对象中好吗? 喜欢上课状态吗?

如果您不想使用useReducer ,则可以在提取时使用Promise.all

useEffect(()=>{
   const stateData = {}
   const fetch1 = axios.get('http://localhost:81/api/myapi/')
   const fetch2 = axios.get('http://localhost:81/api/mysecondapi/')
   Promise.all([fetch1, fetch2]).then(([res1,res2])=>{
     setName(res1.data['name']);
     setPrice(res1.data['price']);
     setColors(res2.data['colors']);
   })
 },[]);

这将导致3x重新渲染,但这与3x DOM更新不同。

如果只想进行一次重新渲染,请将所有更新组合到一个对象中:

Promise.all([fetch1, fetch2]).then(([res1, res2]) => {
  setNamePriceColor({ name: res1.data['name'],
    price: res1.data['price'],
    colors: res2.data['colors'] })
})

您应该尝试链接诺言

useEffect(()=> {
   axios.get('http://localhost:81/api/myapi/')
   .then(res => {
     setName(res.data['name']);
     setPrice(res.data['price']);
   })
   .then(() => axios.get('http://localhost:81/api/mysecondapi/'))
   .then(res => {
     setColors(res.data['colors']);
   })

 },[]);

如果必须axios调用,则react将无法批处理状态更新

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM