【问题标题】:reactjs: How to load json data locally?reactjs:如何在本地加载json数据?
【发布时间】:2020-05-08 03:13:06
【问题描述】:

我编写了一个脚本来显示 json 数据,目前我将数据加载为 runtimeload。 如何修改代码以将其加载为本地?你能帮忙看看吗?谢谢!我想将我的脚本构建为库并构建 json 文件,并且不允许其他人修改这些数据。

错误如下:

./src/components.js
Module not found: You attempted to import ../data/a.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

type State = {
  index: number;
};

type Props = {
 Duration: number;
 Size: number;
 serviceData: typeof service;
};

export class DataFile extends React.Component<Props, State> {
  timerID: number;

  constructor(props: Props) {
    super(props);
    this.state = {
      index: 0,
      testData: this.data(),
    };
    this.timerID=0;
  }

  getData =()=> {
    switch (this.props.serviceData) {
      case service["test_a"] :
        return require('../data/a.json');

      case service["test_b"] :
        return require('../data/b.json');

      case service["test_c"] :
        return require('../data/c.json');

      default:
        return require('../data/c.json');
    }
  }

【问题讨论】:

  • Src 目录中导入您的 json 数据 文件夹。
  • 谢谢。我想用我的代码构建这些 json 数据。其他人可以将其用作库(没有 data.json 列表),但我不想让他们修改数据。

标签: javascript json reactjs typescript


【解决方案1】:

您应该在您的代码中操作一个 JS 对象来生成 JSON 和 stringify it as JSON,当您想要显示它时。

最终您可以使用大多数浏览器中可用的LocalStorage feature 来存储您生成的 JSObject 以进行字符串化。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2019-09-04
    • 1970-01-01
    • 2018-04-23
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多