简体   繁体   English

如何从浏览器读取本地 JSON 文件?

[英]How to read a local JSON file, from the browser?

I know this issue has been discussed before, but all solutions i have found are from years ago, and do not work.我知道之前已经讨论过这个问题,但是我找到的所有解决方案都是几年前的,并且不起作用。

What i need to do, is to load some config fields from a JSON file, sitting in the public directory of my React app.我需要做的是从位于我的 React 应用程序的公共目录中的 JSON 文件加载一些配置字段。 Just a static asset, outside of the build process只是一个静态资产,在构建过程之外

When i try fetching it using AJAX, i get an error on an "Unexpected token ':'".当我尝试使用 AJAX 获取它时,出现“意外令牌':'”错误。 My config.json file looks simply like this:我的 config.json 文件看起来很简单:

{
    "name": "yoyo"
}

It's located in the public directory of a create-react-app program.它位于 create-react-app 程序的公共目录中。 Is there any way this can be done?有什么办法可以做到吗?

Edit: everything is working, i just had some stupid mistake编辑:一切正常,我只是犯了一些愚蠢的错误

Why don't you just import it instead of doing request?你为什么不直接导入它而不是做请求? If you are doing it for any reason, have you tried something like JSON.parse ?如果您出于任何原因这样做,您是否尝试过类似JSON.parse

I updated my question when I noticed you wanted to load a JSON file from the public directory of your project.当我注意到您想从项目的公共目录加载 JSON 文件时,我更新了我的问题。

To do this, use fetch and load the file present from the public folder, then set it for use inside your main component (eg: App.js ).为此,请使用fetch并加载public文件夹中存在的文件,然后将其设置为在您的主要组件中使用(例如: App.js )。

Here's an example using React Hooks:这是一个使用 React Hooks 的例子:

import React from "react";
import "./styles.css";

export default function App() {
  const [characters, setCharacter] = React.useState(null);

  React.useEffect(() => {
    fetch("names.json")
      .then(results => results.json())
      .then(character => setCharacter(character));
  });
  return (
    <div className="App">
      <h1>Star Wars names!</h1>
      <ul>
        {characters.map(character => (
          <li key={character.name}>{character.name}</li>
        ))}
      </ul>
    </div>
  );
}

Working example using the new useEffect hook here在这里使用新的useEffect钩子的工作示例

Working example using good old componentDidMount here在这里使用旧的componentDidMount工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM