[英]simulating hook useState in React.Component scope problem of state
Good Morning, I am trying to create a function in my class React.Component to allow modify a state value with a function. Good Morning, I am trying to create a function in my class React.Component to allow modify a state value with a function.
setCurrentIndex(update) {
if (typeof update === 'function') {
let newValue = update(this.state.currentIndex)
this.setState({ currentIndex: newValue })
} else {
this.setState({ currentIndex: update })
}
}
The problem is that when I execute this function in a child of my component, javascript says that this.state.currentIndex does not exist.问题是,当我在我的组件的子组件中执行此 function 时,javascript 说 this.state.currentIndex 不存在。
Here is my constructor:这是我的构造函数:
constructor(props) {
super(props)
this.state = {
currentIndex: props.index
}
}
Thank you, Best Regards, Fernando Moreno.谢谢你,最好的问候,费尔南多·莫雷诺。
Thanks to HMR, he replies to me the solution in a comment of the question, you just need to do this function as arrow function like this.感谢HMR,他在问题的评论中回复了我的解决方案,你只需要像这样像箭头function那样做这个function。
setCurrentIndex = (update) => {
if (typeof update === 'function') {
let newValue = update(this.state.currentIndex)
this.setState({ currentIndex: newValue })
} else {
this.setState({ currentIndex: update })
}
}
Thank you!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.