首页 > 解决方案 > 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;

标签: javascriptreactjsfunctionapijsx

解决方案


解决这个问题的正确方法是从 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;


推荐阅读