node.js - '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;
解决方案
您正在使用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;
让我知道这是否有帮助。
推荐阅读
- html - 添加文本意外地将容器向下推
- javascript - 从控制器 Spring 中的 js/ajax 获取 JSON 不起作用
- javascript - node.js多次插入行sql
- azure - Azure Active Directory 文件处理程序不会立即出现
- python - ValueError:X 每个样本有 57 个特征;期待 283 在使用 ML 的文本分类中
- python - Python:复数的 Exp 不起作用
- ms-access - 访问形式:间歇性运行时错误 424
- php - Laravel / Ajax:突出显示函数内部不活动或活动的颜色
- regex - 正则表达式匹配字符串的第一部分(直到第一次出现的空格字符),如果它不包含序列 ;host=
- instagram - instagram 基本显示 API 获取请求不起作用?