[英]Add local json file to fetch objects in React
嗨,我想知道什么是從本地文件中獲取 JSON 對象的最佳方法,該文件采用以下格式,以從這些 JSON 列表中呈現鍵值列表。 我試圖導入如下所述的文件,但它徒勞無功。 我想知道如何從本地 json 文件中獲取這些鍵值對以使用 jsx 顯示。 任何線索將不勝感激。 例如,如果我想顯示“約翰在下午 12 點 20 分接到來自美國的電話”。 John 在 Calls 下作為 name ID 傳遞,在 States 下作為 location 傳遞。
{"Calls":[there are list of key values pairs
],
"States":[there are a list of key value pairs],
"time:[list of key value pairs]"}
反應代碼:
import jsonData from "./example.json";
const loadData = () => JSON.parse(JSON.stringify(jsonData));
constructor() {
super();
this.state = {
userList: []
};
}
componentWillMount() {
axios.get('./example.json') // JSON File Path
.then( response => {
this.setState({
userList: response.data
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
const usersList = this.state.userList;
let usersListBlock = '';
if(usersList.length > 0) {
usersListBlock = usersList.map( obj => {
return (
<Usercard key={obj.id} id={obj.id} id={obj.number} name={obj.name} />
)
})
}
return(
<div className="row container">
{usersListBlock}
</div>
)
}
你可以通過導入直接使用json文件,然后你可以直接使用json對象或將其設置為狀態。 像您已經完成的那樣導入 Json 文件
import jsonData from "./example.json";
然后將其設置為 state 或直接使用
componentWillMount() {
this.setState({userList:jsonData })
}
我遇到了同樣的問題,嘗試將 JSON 文件保存在公共文件夾中,然后使用 axios.get('example.json') 調用它,它對我來說很好用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.