【问题标题】:Passing axios data from a utility file to a component将 axios 数据从实用程序文件传递到组件
【发布时间】:2021-04-14 08:33:45
【问题描述】:

在我的 React 应用中,我使用 axios 从 API 返回数据。

api-helper.js

export const getData = async () => {
    axios
        .get(API_DOMAIN)
        .then(response => {
            const resp = response.data;
            console.log(resp);
        })
        .catch(error => console.log('get error', error));
};

在控制台日志中,正确返回了JSON数据:

{
"content": {
"code": "CAT33",
"name": "Death Star ",
"slug": "death-start-",
"trustFriendlySlug": false,
"description": "",
"facetFilters": [
...// additional data

但是,在我的父组件中,当我尝试在 ComponentDidMount 中使用此数据时,它返回的是 HTML 字符串而不是 JSON 数据:

data: "<!DOCTYPE html>↵<html lang="en">↵  <head>↵    
headers: {accept-ranges: "bytes", connection: "keep-alive", content-encoding: "gzip", content-type: "text/html; charset=UTF-8", date: "Fri, 08 Jan 2021 15:49:27 GMT", …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCreden

parentComponent.js

import { getData } from '../../utils/api-helper';


class parentComponent extends Component {
    constructor(props) {
        super(props);

                this.state = {
                   content: {
                     code: '',
                     name: '',
                     facetFilters: [],
                   },
               };

    componentDidMount() {
        axios.get(getData()).then(result => {
            console.log('result', result);
            this.setState({ result });
        });
    }
}

我认为在 componentDidMount 中使用 axios.get 以及来自我的 api-helper 的请求会显示相同的结果。导入数据的正确方法是什么。我看过How to get valid JSON response from axios library using nodeJSCan't set state in react等示例

但是,与那些答案不同,我试图将数据从我的父组件传递到其他组件。处理这些数据的正确方法是什么?

【问题讨论】:

  • 你在做axios.get(getData()),你已经在getData()里面有一个axios.get,只需检查getData()返回什么,加上那个函数中的返回,或者传递api_domain而不是getData()在 componentDidMount

标签: reactjs axios


【解决方案1】:

您首先需要在您的辅助函数中返回,然后在您的组件上挂载等待响应并将其设置为状态

export const getData = async () => {
let resp
   await axios
        .get(API_DOMAIN)
        .then(response => {
            resp = response.data;
            console.log(resp);
        })
        .catch(error => console.log('get error', error));
return resp
};
componentDidMount() {
async function fetchInitial(){

const resp = await getData()
console.log(resp)
}
fetchInitial()
}

【讨论】:

  • 由于某种原因,这将我在辅助函数中的数据返回为undefined。但是,我重写了辅助函数并使用您的 componentDidMount 解决方案最终使其正常工作。非常感谢您的帮助。
  • 很高兴我能帮上忙。是的,我无法像我希望的那样彻底测试我的解决方案,因为我不知道你从哪个 api 中提取,但只要你能够提出解决方案。
猜你喜欢
  • 2020-11-24
  • 2021-07-19
  • 2017-02-27
  • 2019-05-05
  • 2012-07-07
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
相关资源
最近更新 更多