亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在模塊導出 ReactJs 上導出 Axios 響應

如何在模塊導出 ReactJs 上導出 Axios 響應

白衣染霜花 2023-08-18 09:56:30
我需要在 module.exports 上導出 axios 響應的結果。這是我的代碼:品牌.jsvar 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這是瀏覽器上顯示的錯誤:怎么解決這個問題呢?
查看完整描述

1 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

你可以這樣做。


// 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>

  )

}


查看完整回答
反對 回復 2023-08-18
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號