[英]Load JSON file from S3 bucket to React component
我需要從https://s3.eu-central-1.amazonaws.com/easy-client-assets/HomeView.json
加載我的數據文件並在我的組件中使用它。
就像是:
import Data from 'https://s3.eu-central-1.amazonaws.com/easy-client-assets/HomeView.json'
知道我該怎么做嗎?
您可以使用加載程序並將其配置為在webpack中使用。 使用webpack> = 2.0.0時,您不需要加載程序。 Webpack將自動處理導入。 這是加載程序模塊的鏈接 。
請嘗試此操作以便您理解。
xyz.json
//單個數據[{age:21}]
//多個數據[{age:24},{age:35},{age:25}]
import data from '../components/xyz.json';
Const parsedJson = JSON.parse(data);
// accessing single data
Console.log(parsedJson.age);
// accessing multiple data in JSON
Console.log(parsedJson[0].age);
Console.log(parsedJson[1].age);
// convert Json to string
Console.log(JSON.stringify(parsedJson));
我希望它能給您一些想法。
如果沒有某種 web pack 插件,您將無法使用 import 語句引用 S3 文件。 導入僅適用於本地文件。
我最近解決了一個類似的情況,我想使用 s3 來托管配置文件。
我用一個useEffect
鈎子解決了這個問題,並從一個 url fetch
加載文件。 對於本地開發,我使用serve
來托管本地版本,確切的 url 是 .env 配置值(並使用dot-env
來處理不同的構建環境)。
(注意,我幾乎只使用功能性反應組件。您可以將其轉換為類組件並使用componentDidMount
)
const [data, setData] = useState([]);
useEffect(()=>{
fetch(process.env.REACT_APP_CONFIG_URL)
.then(response => response.json())
.then((jsonData) => {
// jsonData is parsed json object received from url
setData(jsonData)
})
.catch((error) => {
// handle your errors here
console.error(error)
})
},[]) //empty array to get `componentDidMount` only and not have the `useEffect` fire on `componentDidUpdate`
這使數據進入反應狀態,並使用緩存頭限制用戶獲取配置文件的頻率。
至於 webpack 插件,這個是存在的,但我沒用過https://github.com/egoist/import-http
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.