提问者:小点点

多个setState处于useEffect中,如何避免重新渲染?


当有多个setState处于useEffect状态时,如何避免重新渲染?

我想做2个API调用和设置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']);
   })
 },[]);

我只需要在所有集合之后进行一次渲染。我知道在每次设置状态后重新渲染是正确的,但是我如何才能使它只执行一次呢?将所有状态放在一个对象中好吗?像阶级国家?


共2个答案

匿名用户

如果你不想使用useReduer,可以使用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']);
   })
 },[]);

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

如果你只想要一个单一的重新渲染,将所有的更新合并到一个对象中:

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

匿名用户

你应该试着把promise锁起来

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调用,则响应将无法批处理状态更新。