首页 > 解决方案 > componentDidMount() 获取本地数据

问题描述

我正在尝试使用存储在项目目录中的 JSON 文件来测试 React 组件。

我不确定我是否以正确的方式进行此操作:

    constructor(props){
    super(props);
    this.state = {
      videoPath: video,
      data: null
    }
  }

  componentDidMount(){
    fetch('../../data/jsonfile.json')
      .then(response => response.json())
      .then(data => this.setState({data}));

  }

我收到一条错误消息: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

JSON 文件开始:

{
    "0":{
        "coords":[
            [
                645.0,
                353.0,
                0.9010798558592796,
                0.0,
                0.0
            ],

所以里面应该有一个<。但是当我在 Chrome 中检查源代码时,jsonfile.json 看起来就像一个 HTML 文件。我在用着create-react-app

标签: jsonreactjs

解决方案


推荐阅读