首页 > 解决方案 > 'TypeError: this is undefined' 在使用功能组件中的类成员时发生

问题描述

我正在尝试通过在单独的 localhost (:9000) 中托管一个简单的 NodeJS API 来使用 NodeJS 将数据传递给 ReactJS 组件。但我遇到了一个错误。

类型错误:这是未定义的

我相信这个错误是由于在功能组件中使用“this”而发生的。但我找不到解决这个问题的方法。

有错误的代码:

import React from 'react';
import ReactDOM from 'react-dom';

class News extends React.Component{


   constructor (props){
      super(props);
      this.state={apiResponse:""};

   }

   callAPI(){
      fetch("http://localhost:9000/testAPI")
      .then(res => res.text ())
      .then(res => this.setState({apiResponse: res}));
      
      
   }

   componentWillMount(){
      this.callAPI();
   }
}

function Newsexport() {
 return (
    <div class="container1">
       <h1>IT WORKS YO!</h1>
      <p>{this.state.apiResponse}</p> 
    </div>
  )
};

export default Newsexport;

使用 NodeJS 托管的简单 API 的代码 (/api/routes/testAPI.js)

var express = require("express");
var router=express.Router();

router.get("/", function(req,res,next){
    res.send("API is working");

});

module.exports=router;

标签: node.jsreactjscomponentsjsx

解决方案


您正在使用this错误的功能组件。此外,您正在一个组件中设置状态并期望另一个组件中的值。而是将两个组件组合在一起,如下所示 -

 class News extends React.Component{

    constructor (props){
      super(props);
      this.state={apiResponse:""};
    }

    callAPI = () => {
      fetch("http://localhost:9000/testAPI")
        .then(res => res.text ())
        .then(res => this.setState({apiResponse: res}));
    }

    componentWillMount(){
      this.callAPI();
    }

    render() {
      return (
        <div class="container1">
          <h1>IT WORKS YO!</h1>
          <p>{this.state.apiResponse}</p> 
        </div>
      )
    }
  }
  export default News;

让我知道这是否有帮助


推荐阅读