【问题标题】:Cant read JSON file with the react production build无法使用反应生产构建读取 JSON 文件
【发布时间】:2020-10-21 17:05:48
【问题描述】:

我有一个简单的反应组件,我正在读取一个 JSON 文件。该文件像这样放在公用文件夹中

root/public/data.json 

我正在读取类似这样的 JSON 文件

class DspTable extends Component {
  componentDidMount() {
    fetch('data.json').then(response => {
            response.json().then(res=> {
                this.setState({ stats: res, loading: false })
            })
        })
   }

 ..
}

当我在本地运行 react 应用程序时,这一切都很好

$ yarn start

但是我需要构建站点并将其部署到 s3(静态托管)。

所以我构建了应用程序

$ yarn build

我看到构建文件夹有 data.json 与 index.html 一起复制。

但是,当我在构建文件夹中打开 index.html 时,我看不到任何内容,因为没有从 JSON 加载数据。

如何使用生产版本加载 JSON 文件?

我正在使用 React 版本 17.0.0。

编辑:这是我的错误。我错过了 s3 存储桶中的存储桶策略。

如果以后有人遇到类似问题,请使用这样的存储桶策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicReadAccess",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

【问题讨论】:

  • 控制台有错误吗? JSON 来自哪里?你做了什么调试? res 的值是多少?

标签: javascript reactjs components


【解决方案1】:

您是否尝试双击 index.html 来启动该文件?如果是这种情况,它将无法正常工作,因为 json 文件的加载将被浏览器阻止。您需要使用服务器(例如 http://localhost:3000)运行构建包。

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2020-10-16
    • 1970-01-01
    • 2018-05-29
    • 2021-05-11
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多