在嵌套函数中反应setState



;console.log(this.state.eremaining(";在startStop((中显示正确的值。然而;setState(("在嵌套函数decrement((中,抛出一个错误";TypeError:无法读取未定义的"的属性"state";。怎么了?

import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
remaining: 0,
}
startStop() {

console.log(this.state.remaining)
function decrement() {
this.setState({
remaining: this.state.remaining + 1
})
}  
}

这很有效。

const decrement = () => {
this.setState({
remaining: this.state.remaining + 1
})
}

this指的是类内部的方法,而不是函数自身作用域中的方法。更改为:

import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
remaining: 0,
}
startStop() {

console.log(this.state.remaining)
decrement() {
this.setState({
remaining: this.state.remaining + 1
})
}  
}

最新更新