如何将json文件返回到React

项目中有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>
        );
    }
};
评论
psunt
psunt

这会呈现JSON中的所有内容

import React, {Component} from "react";
import "./style.scss";
const dictionaryFile = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionaryFile.dictionary.map(elem => (
                    <div>
                       <p>{elem.index}</p>
                       <p>{elem.engwords}</p>
                       <p>{elem.ruswords}</p>
                    </div>
                  ))
                }
            </div>
        );
    }
};
点赞
评论
nsit
nsit

将Json文件放在公共文件夹中,然后从componentDidMount调用

fetch(${process.env.PUBLIC_URL}/dictionary/dictionary.json)

点赞
评论