[英]How to Export Axios Response on Module Export ReactJs
我需要在 module.exports 上導出 axios 響應的結果。 這是我的代碼:
品牌.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
這是瀏覽器上顯示的錯誤:
如何解決這個問題?
你可以這樣做。
// 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>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.