Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React中的JSX函数是否不返回数据?_Javascript_Reactjs_Function_Api_Jsx - Fatal编程技术网

Javascript React中的JSX函数是否不返回数据?

Javascript React中的JSX函数是否不返回数据?,javascript,reactjs,function,api,jsx,Javascript,Reactjs,Function,Api,Jsx,我正在创建一个简单的GETAPI,它收集数据并在前端将其作为基本文本输出。API工作并在控制台中显示数据,但前端没有返回任何内容。请帮助: import React, { Component } from 'react'; import './Cards.css' const data = { name: 'test', hobby: 'test' } function getUsers (data) { fetch('http://localhost:3001/pro

我正在创建一个简单的GETAPI,它收集数据并在前端将其作为基本文本输出。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;

import React,{Component}来自'React';
导入“./Cards.css”
常数数据={
名称:'测试',
爱好:“测试”
}
函数getUsers(数据){
取('http://localhost:3001/profile', {
方法:“GET”,
标题:{
“内容类型”:“应用程序/json”,
}
})
.then((response)=>response.json())
。然后((数据)=>{
console.log('Success:',data)
})
。然后((数据)=>{
返回data.name
})
.catch((错误)=>{
console.error('error:',error)
});
};
功能卡(数据){
返回(
标题

{getUsers(数据)}

在源代码标题中有名的人 ); } 导出默认卡;
我认为如果你链接另一个,你应该返回数据。然后,第一个控制台正确地记录了数据,但第二个没有返回


而且你的函数是异步的,所以它应该在useEffect回调中。

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

import React,{useState,useffect}来自“React”;
导入“/Cards.css”;
常数数据={
名称:“测试”,
爱好:“测试”
};
功能卡(数据){
const[name,setName]=useState(“”)
useffect(()=>{
getUsers()
},[getUsers])
函数getUsers(数据){
取回(“http://localhost:3001/profile", {
方法:“获取”,
标题:{
“内容类型”:“应用程序/json”
}
})
.then(response=>response.json())
。然后(数据=>{
console.log(“成功:”,数据);
})
。然后(数据=>{
setName(data.name)
返回data.name;
})
.catch(错误=>{
控制台错误(“错误:”,错误);
});
}
返回(
标题
{name}

在源代码标题中有名的人 ); } 导出默认卡;
您可以使用
useffect
并按照注释中的说明说明,下面的代码应该有效:

import React, { Component, useEffect } from 'react';
import './Cards.css'

const data = {
    name: 'test',
    hobby: 'test'
}






function Cards (data) {
    const [ users, setUsers] = useEffect('')
    useEffect(() => {
        function getUsers (data) { 
            return fetch('http://localhost:3001/profile', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            }).then((response) => response.json())
            .catch((error) => {
                console.error('Error:', error)
            });
        };
        getUsers(data).then((data) => setUsers(data.name) )
    }, [])
    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>
            {users}
            </p>
            <footer className="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
            </blockquote>
            </div>
        </div>

    );}


export default Cards;
import React,{Component,useffect}来自'React';
导入“./Cards.css”
常数数据={
名称:'测试',
爱好:“测试”
}
功能卡(数据){
const[users,setUsers]=useffect(“”)
useffect(()=>{
函数getUsers(数据){
返回获取('http://localhost:3001/profile', {
方法:“GET”,
标题:{
“内容类型”:“应用程序/json”,
}
}).then((response)=>response.json())
.catch((错误)=>{
console.error('error:',error)
});
};
getUsers(data).then((data)=>setUsers(data.name))
}, [])
返回(
标题

{用户}

在源代码标题中有名的人 );} 导出默认卡;
getUsers
async
,因此需要使用state进行更新。虽然当悬念处于活动状态时,这样的事情应该会更容易->同样,在你的第二个
中。然后
控制台。记录
数据,但不要返回它,因此它将丢失并且不会传递到下一个
。然后
谢谢!还有其他评论的人。这是一个巨大的帮助!在使用上述代码时,我仍然会遇到类似的错误。我研究过它,我想我现在明白了,但我仍然无法找出是什么导致了这个错误。在不做任何调整的情况下,上面的代码给了我以下错误:
“Cards.js:25 Success:{name:“Griffin”,hobby:“Dota 2”}错误:TypeError:无法读取Cards.js:28 Cards.js:25 Success:{name:“Griffin”,hobby:“Dota 2”}index.js:1错误:TypeError:无法读取未定义的at Cards的属性'name'。js:28“
当我用
setName('Griffin')替换
setName(data.name)
时,它能工作吗?因此,设置的状态正在工作。如果I
console.log(data.name)我完全得到了我需要的,但它只是拒绝将数据吐到段落中?这是API中的数据变量造成的。这似乎意味着数据是未定义的。如果在上一个
然后
块中调用
setName
,是否有效。(您在其中记录“成功”)
import React, { Component, useEffect } from 'react';
import './Cards.css'

const data = {
    name: 'test',
    hobby: 'test'
}






function Cards (data) {
    const [ users, setUsers] = useEffect('')
    useEffect(() => {
        function getUsers (data) { 
            return fetch('http://localhost:3001/profile', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            }).then((response) => response.json())
            .catch((error) => {
                console.error('Error:', error)
            });
        };
        getUsers(data).then((data) => setUsers(data.name) )
    }, [])
    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>
            {users}
            </p>
            <footer className="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
            </blockquote>
            </div>
        </div>

    );}


export default Cards;