0

当我在 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 之后重新渲染是正确的,但是我怎样才能让它只做一个呢?把所有状态都放在一个对象中好吗?像阶级状态?

4

2 回答 2

3

如果您不想使用useReducer,可以Promise.all与您的 fetches 一起使用

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'] })
})
于 2019-07-11T13:29:35.460 回答
1

你应该尝试链接承诺

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 将无法批量更新状态

于 2019-07-11T13:18:20.717 回答