在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之后重新渲染是正确的,但是我怎样才能做到这一点呢? 将所有状态都放在一个对象中好吗?喜欢上课状态吗?
答案 0 :(得分:2)
如果您不想使用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']);
})
},[]);
这将导致3倍的重新渲染,但这与3倍的DOM更新不同。
如果只想进行一次重新渲染,请将所有更新组合到一个对象中:
Promise.all([fetch1, fetch2]).then(([res1, res2]) => {
setNamePriceColor({ name: res1.data['name'],
price: res1.data['price'],
colors: res2.data['colors'] })
})
答案 1 :(得分: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
通话,则无法进行batch the state update的反应。