React native 调用方法时,状态消失

React native 调用方法时,状态消失,react-native,state,React Native,State,我正在做一个班级项目,我的状态正在消失。在componentDidMount console.log(this.state)之后,一切正常。我启动setInterval并调用inc()。不知何故,当我进入inc()时,这个州就被消灭了 从“React”导入React; 从“react native”导入{TextInput,按钮,样式表,文本,视图}; 从“./styles/styles.js”导入样式; 调试=真 导出默认类App扩展React.Component{ 构造函数(){ 超级()

我正在做一个班级项目,我的状态正在消失。在componentDidMount console.log(this.state)之后,一切正常。我启动setInterval并调用inc()。不知何故,当我进入inc()时,这个州就被消灭了

从“React”导入React;
从“react native”导入{TextInput,按钮,样式表,文本,视图};
从“./styles/styles.js”导入样式;
调试=真
导出默认类App扩展React.Component{
构造函数(){
超级()
this.state={timer:'WORK',
工作时间:25*60+0,
休息时间:5*60+0,
当前时间:0,
剩余时间:null,
分:0,,
第0节,
startFlag:false,
resetFlag:false}
}
componentDidMount(){
this.interval=setInterval(this.inc,10000)
if(debug)console.log('COMPONENTDIDMOUNT',this.state)
}
静态getDerivedStateFromProps(下一步,上一步){
if(debug)console.log('GETDERIVEDSTATEFROMPROPS',prevState)
返回空
}
shouldComponentUpdate(下一步,下一步状态){
if(debug)console.log('SHOULDCOMPONENTUPDATE',nextState)
返回真值
}
componentDidUpdate(){
if(debug)console.log('COMPONENTDIDUPDATE',this.state)
}
组件将卸载(){
if(debug)console.log('COMMPONENTWILLUNMOUNT',this.state)
}
startToggle(){
如果(endTime==null)this.setState({remainingTime:this.state.workTime,
startFlag:!this.state.startToggle})
else this.setState({remainingTime:!this.state.startFlag})
}
textTime(){
让min=Math.floor(this.state.remainingTime/60).toString()
let sec=(this.state.remainingTime%60)
如果(秒<10)秒?'0'+秒:秒toString()
this.setState({min:min,sec:sec})
}
公司(){
console.log(this.state)
}
captureInput(){}
render(){
console.log('RENDER',this.state)
返回(
{`${this.state.timer+'timer'}`}
12:00
this.startToggle()}/>
this.resetToggle()}/>
“工作计时器:”
最小值:
{this.captureInput(text)}
/>
证券交易委员会:
{this.captureInput(text)}
/>
'中断计时器:'
最小值:
{this.captureInput(text)}
/>
证券交易委员会:
{this.captureInput(text)}
/>
)
}

}
将您的
inc
方法声明更改为

inc = () => {
  ...
}
根据您的代码,
这个
内部
inc()
不是指
组件
,因此您也不会得到
状态

希望这会有帮助

您有两种选择:

  • inc()
    更改为
    inc=()=>
  • this.inc
    更改为
    this.inc.bind(this)