【问题标题】:React js read file to fetchReact js读取文件以获取
【发布时间】:2020-02-13 08:26:57
【问题描述】:

我必须读取一个json文件,我按照以下代码:stackoverflow

尝试评论中显示的示例,但它不适合我。

我必须阅读我在本地拥有的这个文件,但我没有成功。

你能帮帮我吗?

链接:Codesandbox

代码:

fetch("/user.json")
  .then(res => res.json())
  .then(res => res.results)
  .then(res => {
    console.log(res);
    let u = res.map((suggestion, i) => ({
      label: suggestion.email,
      name: suggestion.name.first,
      surname: suggestion.name.last,
      address: suggestion.location.street.name,
      email: suggestion.email,
      picture: suggestion.picture.thumbnail
    }));
    let options =
      inputLength === 0
        ? []
        : u.filter(suggestion => {
            const keep =
              count < 5 &&
              suggestion.label &&
              suggestion.label.slice(0, inputLength).toLowerCase() ===
                inputValue;
            if (keep) count += 1;
            return keep;
          });
    this.setState({ options });
  })
  .catch(e => console.log("Er:", e));

【问题讨论】:

  • 有什么问题?现在发生了什么?预期的行为是什么?
  • 我想阅读该文件。他没有阅读它并进入获取捕获条件。但是,如果您尝试我在codesandbox 上发布的示例,您会立即看到它。
  • user.json 文件在哪里?如果它在公共文件夹中,则获取 uri 参数应该是 ${process.env.PUBLIC_URL} + "/user.json" 实际上我尝试了您的 CodeSandbox 演示,它可以工作;但它不在您的本地环境中?
  • 我已经尝试打印 process.env.PUBLIC_URL 返回未定义。
  • 请更新您的问题描述。

标签: javascript json reactjs fetch fetch-api


【解决方案1】:

你可以只使用 import 或 require 如下:

const data = require("./myFile.json")
import data from "./myFile.json"

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 2020-10-06
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    • 2021-09-29
    • 2018-08-29
    相关资源
    最近更新 更多