react中使用setState报错:
Uncaught (in promise) Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

报错原因是在render函数中使用setState造成state改变,state改变就会重新渲染render,每次render又会setState,就会造成页面死循环。
解决方法:
- 使用箭头函数
() => {
函数体
setState()
}
- 在有条件的代码块中使用setState
const { code, data, message } = await fetchFn(_params);
if (code === SUCCESS) {
setNameList(_params.products);
...
...
} else {
console.error(message);
...
...
}

本文探讨了在React中如何避免因不当使用setState导致的无限循环更新问题。具体介绍了错误用法及其背后的原理,并提供了使用箭头函数和条件判断来解决问题的方法。

724

被折叠的 条评论
为什么被折叠?



