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);
...
...
}