首页 > 解决方案 > 在嵌套函数中反应 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
        })
    }  
  }

标签: reactjsjasmine

解决方案


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
        })
    }  
  }

推荐阅读