javascript - React中的JSX函数不返回数据?
问题描述
我正在创建一个简单的 GET API,它收集数据并将其作为基本文本输出到我的前端。API 工作并在控制台中显示数据,但前端没有返回任何内容。请帮忙:
import React, { Component } from 'react';
import './Cards.css'
const data = {
name: 'test',
hobby: 'test'
}
function getUsers (data) {
fetch('http://localhost:3001/profile', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data)
})
.then((data) => {
return data.name
})
.catch((error) => {
console.error('Error:', error)
});
};
function Cards (data) {
return (
<div id='cards'>
<div className="card-header" id='card-header'>
Header
</div>
<div className="card-body" id='card-body'>
<blockquote className="blockquote mb-0">
<p>
{getUsers(data)}
</p>
<footer className="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
</blockquote>
</div>
</div>
);
}
export default Cards;
解决方案
解决这个问题的正确方法是从 API 获取数据(您可以通过useEffect
钩子触发调用),将结果存储在组件的状态中,然后在 JSX 中使用此状态值。
import React, { useState, useEffect } from "react";
import "./Cards.css";
const data = {
name: "test",
hobby: "test"
};
function Cards(data) {
const [name, setName] = useState("")
useEffect(() => {
getUsers()
}, [getUsers])
function getUsers(data) {
fetch("http://localhost:3001/profile", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.then(data => {
setName(data.name)
return data.name;
})
.catch(error => {
console.error("Error:", error);
});
}
return (
<div id="cards">
<div className="card-header" id="card-header">
Header
</div>
<div className="card-body" id="card-body">
<blockquote className="blockquote mb-0">
<p>{name}</p>
<footer className="blockquote-footer">
Someone famous in <cite title="Source Title">Source Title</cite>
</footer>
</blockquote>
</div>
</div>
);
}
export default Cards;
推荐阅读
- python - python3中的可迭代类
- javascript - 提交前检查复选框是否选中
- hibernate - Hibernate Search 直接计数,而不是使用 Lucene 和 Elasticsearch 进行常规查询
- css - JavaFx 和 TornadoFX 在 CSS 或 TypeSafeCSS 中更改边距
- sql-server-2008 - 过去 24 个月的数据
- wordpress - 如何在一个菜单下显示多种类型的待处理帖子
- java - 如何在android中的领域更新
- html - 如何定位文本小部件?
- javascript - 无法返回 url 字符串,尽管能够对其进行 console.log。不知道为什么
- css - 无法在反应中导入字体(node-sass)