为什么我可以 console.log 值而不是 setState?

Why can I console.log the value but not setState?

如果有一个非常明显的解决方案,我提前道歉,但我是 React.js 的新手。

我正在使用 google-translate api 构建一个简单的翻译器 component.The 文本输入存储在状态中并由 translateInput() 使用,然后我想要用翻译后的文本设置状态。不幸的是,我不能,但是我可以 console.log googleTranslate 函数返回的值。为什么会这样?我必须以某种方式绑定回调函数吗?

谢谢!

import React, { Component } from "react";
import { googleTranslate } from '../utils/googleTranslate';

class Translator extends Component {
    constructor(){
        super();

        this.state = {
             input:'',
             translatedInput: '',
        }
    }

    handleTextInput = e => {
        this.setState({input:e.target.value})
    }

    translateInput = () => {
        googleTranslate.translate([this.state.input],"en", "de", 
        function (err, translations){        
      //this.setState({translatedInput:translations.translatedText}) 
      //TypeError: Cannot read property 'setState' of undefined
        console.log(translations.translatedText)
        })
    }

您正在使用的函数的上下文无法通过 this 关键字访问组件,因为您正在使用 function 关键字创建函数作用域。使用箭头函数应该可以解决问题:

 translateInput = () => {
        googleTranslate.translate([this.state.input],"en", "de", 
        (err, translations) => {        
      this.setState({translatedInput:translations.translatedText}) 
        console.log(translations.translatedText)
        })
    }