Javascript 如何将函数返回的值放入React中的另一个类中

Javascript 如何将函数返回的值放入React中的另一个类中,javascript,reactjs,Javascript,Reactjs,所以我试图创建一个服务,在整个项目中使用它,通过API调用从服务器检索一些数据。函数看起来像这样 export function data(){ const proxyurl = "https://cors-anywhere.herokuapp.com/"; fetch(proxyurl+process.env.REACT_APP_TEXT_API) .then(res => res.json()) .then(json => { return js

所以我试图创建一个服务,在整个项目中使用它,通过API调用从服务器检索一些数据。函数看起来像这样

export function data(){
  const proxyurl = "https://cors-anywhere.herokuapp.com/";
  fetch(proxyurl+process.env.REACT_APP_TEXT_API)
    .then(res => res.json())
    .then(json => {
     return json;
    })
}
我试图通过这样做来访问React组件中返回的json

import {data} from '../../../../services/textService/textApi'



class Error404Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: "Something"
    }
  }

   componentDidMount() {
   this.setState({
     data: this.data()
   })

  }


问题是状态变量“data”值设置为未定义。如何访问我的函数返回的数据?

您忘记返回
获取

export function data(){
  const proxyurl = "https://cors-anywhere.herokuapp.com/";
  // added return statement
  return fetch(proxyurl+process.env.REACT_APP_TEXT_API)
    .then(res => res.json())
    .then(json => {
     return json;
    })
}
但是这也会有一些问题,您需要使用
await/async

async componentDidMount() {
   // using await / async 
   const newData = await data()
   this.setState({
     data: newData
   })
}

如果要调用来自“…”
import{data}的
data
,则不使用
this.data()
<代码>此
将来自您的组件,而不是来自导入。

预期返回内容的JavaScript函数必须显式返回它们。下面是一个返回承诺的原始post代码示例。我已经将函数调用抛出到一个钩子中,但是同样的事情也可以在基于类的组件中完成

import React, {useEffect} from "react";
import ReactDOM from "react-dom";

function data(){
  return fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => res.json())
    .then(json => json)
}

function App() {
  useEffect(() => {
    data().then(resp => console.log(resp))
  })

  return (
    <div />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React,{useffect}来自“React”;
从“react dom”导入react dom;
函数数据(){
返回获取('https://jsonplaceholder.typicode.com/todos/1')
.then(res=>res.json())
.然后(json=>json)
}
函数App(){
useffect(()=>{
data().then(resp=>console.log(resp))
})
返回(
);
}
const rootElement=document.getElementById(“根”);

ReactDOM.render(

的可能副本您无法直接在组件中获得响应。您需要首先将react组件与Redux存储连接。使用“react Redux”插件。什么?为什么需要react redux?它会很好地工作。我想你还需要检查解决方案以了解。我刚刚尝试了你的解决方案,但当我执行const data=wait data()时,我收到一个错误,说数据不是函数@Octavian请确保您以正确的方式导入
数据
。如果您没有导入,
数据
将被取消定义,并将为您提供该信息error@Octavian另外,刚刚进行了一次编辑,有一个小错误,请尝试一下。我需要能够在渲染函数之外导入此服务,这就是我使用函数和不是类。在这个答案中,
数据
不在
渲染
函数中。它与组件分离,可以从任何地方导入。你能给我一个例子说明如何在类中导入它吗?导入或使用类不是OP代码失败的原因。一步一步地进行:将函数放在同一个位置文件作为组件,然后找出如何返回承诺并在
componentDidMount
中调用函数。在承诺返回中设置状态。然后将函数移动到API文件中。