【问题标题】:How to Export Axios Response on Module Export ReactJs如何在模块导出 ReactJs 上导出 Axios 响应
【发布时间】:2020-11-19 17:19:38
【问题描述】:

我需要在 module.exports 上导出 axios 响应的结果。 这是我的代码:

brand.js

var axios = require('axios');

module.exports = (async function() {
    try {
        const { data } = axios.get('http://localhost:8000/api/v1/setting/index');
        console.log(data.data.initial);
        return {
            name: data.data.name,
            desc: data.data.description,
          };      
    } catch (err) {
        console.log(err);
      }      
})();

我尝试导入结果以用于另一个文件。 这是我的代码。


import React from 'react';
const {brand} = await require("brand.js");
  
class Dashboard extends Component {   
    render(){
        const name = brand.name
        const desc = brand.description;
        return (
        <h1>{title} | {description}</h1>
        );        
    }
}  

我的代码的结果是:

Can not use keyword 'await' outside an async function

这是浏览器上显示的错误:

如何解决这个问题?

【问题讨论】:

  • 您是否尝试过将await 放在brand.js 中的axios.get() 之前,而不是放在require() 之前?
  • 这能回答你的问题吗? exporting after promise finishes
  • 你必须在导入的(必需的)Promise 对象上使用.then()
  • 我在axios前面加了await,但是错误依旧存在。

标签: javascript reactjs axios


【解决方案1】:

你可以这样做。

// brand.js

import axios from 'axios';

export const fetchData = async () => {
  let response;

  try {
    response = await axios.get(url, config);
  } catch (e) {
    // catch error
    throw new Error(e.message)
  }

  // if success return value
  return response?.data ? response?.data : null // or set initial value
}

然后在你的 React 中

import { fetchData } from './path/to/fetchData';

const response = fetchData();

const MyComponent = (props) => {
  return (
    <div>name: {response.data.name} | desc: {response.data.description}</div>
  )
}

【讨论】:

猜你喜欢
  • 2021-05-06
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
相关资源
最近更新 更多