reactjs - 在嵌套函数中反应 setState
问题描述
startStop() 中的“console.log(this.state.remaining)”显示了正确的值。然而,嵌套函数 decrement() 中的“setState()”会引发错误“TypeError: Cannot read property 'state' of undefined”。怎么了?
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
})
}
}
解决方案
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
})
}
}
推荐阅读
- c# - 如何选择**数据库表
- php - 不使用 curl 获取个人数据
- jakarta-ee - ActiveMQ 嵌入式推荐
- javascript - 为什么将新创建的元素插入现有元素会解析 [Object HTMLElement]?
- bash - error while running shell script through jenkins pipeline
- git - How do I limit what I pull down for my gatsby site from my repo?
- android - 相同的数据出现在整个 recyclerview 中
- angularjs - Tabs navigation issue with search button?
- javascript - 匿名函数名称未显示
- java - 使用java在EPS文件中添加元数据