您需要将依赖项数组添加到
useEffect
. 从依赖关系数组中排除项目可能会导致无限的更新链。
添加依赖项数组作为的第二个参数
使用效果
:
useEffect(()=>{
setChartData({
labels: ['john','kevin','george','mike','oreo'],
datasets:[
{
label: 'label',
data: [12,55,34,120,720],
borderColor: 'green',
backgroundColor: 'blue',
},
],
})
},[])
setChartOptions({
responsive:true,
plugins:{
legend:{
position:'top'
},
title:{
display:true,
text:'text from tittle'
}
}
}, [chartOptions, chartData]) // effect will run when either changes
只想运行一次效果?
如果您想运行一个效果并只清理一次(在装载和
unmount),可以将空数组([])作为第二个参数传递。这
告诉React您的效果不依赖于道具的任何值
或状态,因此它永远不需要重新运行。这不是作为特殊的
案例–它直接从依赖项数组总是
作品
在中了解更多信息
docs