【问题标题】:How to display the content of a JSON file in React?如何在 React 中显示 JSON 文件的内容?
【发布时间】:2021-09-12 15:32:09
【问题描述】:

我的公共文件夹中有一个静态 JSON 文件,我想在 React (NextJS) 组件中输出内容。只需再次将所有内容显示为 JSON。

import data from '../../public/static/somedata/data.json';

const DummyComponent = () => {
  return (
    <div className="box">{data}</div>
  );
};

目前我收到错误:

对象作为 React 子对象无效

有没有办法在 React 组件中显示原始 JSON 内容?

【问题讨论】:

    标签: json reactjs typescript react-redux next.js


    【解决方案1】:

    这应该可以完成工作:

    <div className="box"><pre>{JSON.stringify(data, null, 2)}</pre></div>
    

    【讨论】:

    • 哇 .. 我试过这个没有进一步的论点。现在可以了,非常感谢。
    【解决方案2】:

    试试 JSON.stringify()

    import data from '../../public/static/somedata/data.json';
    
    const DummyComponent = () => {
      return (
        <div className="box">{JSON.stringify(data)}</div>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多