白衣染霜花
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>
)
}
添加回答
舉報
0/150
提交
取消