[英]this.setState is not working in componentDidUpdate
There is a some problem with this code, i think because `` setState is not working in this code.这段代码有一些问题,我认为是因为 `` setState 在这段代码中不起作用。
this.setState({
showTooltip: true,
toolTipsValue: message,
error: true
})
Before click on a button单击按钮之前
this.props.loginRes = {
responseCode: 1,
result: {}
}
After Click on button点击按钮后
prevProps.loginRes = {
responseCode: 1,
result: {}
}
this.props.loginRes = {
responseCode: 1,
result: {
data: {},
statusCode: 1,
statusMessage: 'Invalid email/mobile'
}
}
componentDidUpdate(prevProps, prevState) {
if (this.props.loginRes !== prevProps.loginRes) {
const message = this.props.loginRes.result.statusMessage;
this.setState({
showTooltip: true,
toolTipsValue: message,
error: true
})
}
}
Error Message Error Message Link错误信息错误信息链接
The error this.setState is not a function is triggered because you didn't bind the onClick
handler.错误this.setState is not a function被触发,因为您没有绑定
onClick
处理程序。 As a result this
points to the window
object and not to the instance of your React class component.结果
this
指向window
对象而不是 React 类组件的实例。 And the window
object doesn't have setState()
function as its property - that's what the error message says.并且
window
对象没有setState()
函数作为其属性 - 这就是错误消息所说的。
To fix this error either bind the onClick
handler in the class constructor or rewrite the handler using an arrow function.要修复此错误,请在类构造函数中绑定
onClick
处理程序或使用箭头函数重写处理程序。
Using setState
inside componentDidUpdate
in the way you did should not cause endless loop.以您所做的方式在
componentDidUpdate
内使用setState
不应导致无限循环。
As an addition to winwiz1.作为winwiz1的补充。 (What he says is correct).
(他说的是对的)。
You are commparing two objects in the componentDidUpdate function.您正在比较 componentDidUpdate 函数中的两个对象。 Comparing two objects with !== will not work.
用 !== 比较两个对象是行不通的。 The answer why it isn`t working can be found here: Comparing two objects
可以在这里找到为什么它不起作用的答案: 比较两个对象
The solution is lodash with isEqual, example can be found here: Depp comparison between 2 objects解决方案是使用 isEqual 的 lodash,示例可以在这里找到: Depp compare between 2 objects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.