React js read file to fetch

问题描述 投票:0回答:1

我必须阅读一个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));
javascript json reactjs fetch fetch-api
1个回答
0
投票

您可以只使用import或要求如下:

const data = require("./myFile.json")
import data from "./myFile.json"
© www.soinside.com 2019 - 2024. All rights reserved.