项目中有json,其中包含我需要在组件中显示的数据。如何正确访问React中的JSON文件并从JSON输出数据?
data.json
{
"dictionary": [
{
"index": "1",
"engwords": "Hello",
"ruswords": "Привет"
},
{
"index": "2",
"engwords": "How are you?",
"ruswords": "Как твои дела?"
},
{
"index": "3",
"engwords": "How old are you?",
"ruswords": "Сколько тебе лет?"
}
]
}
component.js
import React, {Component} from "react";
import "./style.scss";
const dictionary = require ('./../../dictionary/dictionary.json');
export default class Test extends Component {
render() {
return (
<div className="test">
{dictionary.map(elem => (
<p>{elem}</p>))}
</div>
);
}
};
这会呈现JSON中的所有内容
将Json文件放在公共文件夹中,然后从componentDidMount调用
fetch(
${process.env.PUBLIC_URL}/dictionary/dictionary.json
)