Javascript 模拟React中的钩子使用状态。状态的组件范围问题
早上好, 我试图在类React.Component中创建一个函数,以允许使用函数修改状态值Javascript 模拟React中的钩子使用状态。状态的组件范围问题,javascript,reactjs,Javascript,Reactjs,早上好, 我试图在类React.Component中创建一个函数,以允许使用函数修改状态值 setCurrentIndex(update) { if (typeof update === 'function') { let newValue = update(this.state.currentIndex) this.setState({ currentIndex: newValue }) } else {
setCurrentIndex(update) {
if (typeof update === 'function') {
let newValue = update(this.state.currentIndex)
this.setState({ currentIndex: newValue })
} else {
this.setState({ currentIndex: update })
}
}
问题是,当我在组件的子组件中执行此函数时,javascript会说this.state.currentIndex不存在
这是我的构造函数:
constructor(props) {
super(props)
this.state = {
currentIndex: props.index
}
}
谢谢,,
顺致敬意,
Fernando Moreno。多亏了HMR,他在对问题的评论中回答了我的答案,你只需要像箭头一样做这个函数
setCurrentIndex = (update) => {
if (typeof update === 'function') {
let newValue = update(this.state.currentIndex)
this.setState({ currentIndex: newValue })
} else {
this.setState({ currentIndex: update })
}
}
谢谢大家! 多亏了HMR,他在对问题的评论中回答了我的答案,你只需要像箭头一样做这个函数
setCurrentIndex = (update) => {
if (typeof update === 'function') {
let newValue = update(this.state.currentIndex)
this.setState({ currentIndex: newValue })
} else {
this.setState({ currentIndex: update })
}
}
谢谢大家! 您是否通过道具将函数传递给子组件?不确定我是否误解了您的问题,但react挂钩仅在functional componentsTry中可用,以使
setCurrentIndex
和arrow函数:setCurrentIndex=update=>{
下次请提供您得到的确切错误。子项不会自动从父项继承状态/成员函数。您必须通过props@HMR将函数更改为箭头函数效果很好!谢谢!您是否通过道具将函数传递给子组件?不确定我是否误解了您的说明问题,但react钩子仅在functional componentsTry中可用,用于生成setCurrentIndex
和箭头函数:setCurrentIndex=update=>{
下次请提供您得到的确切错误。子项不会自动从父项继承状态/成员函数。您必须通过props@HMR把函数改为箭头函数做的不错!谢谢!