Uncaught (in promise) SyntaxError: Unexpected token in React

时间:2021-04-29 17:05:50

标签: reactjs

我遇到了这个错误

VM305:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我不知道为什么。我的json数据:

[
  {
   "id": 1,
    "title": "Avatar",
    "distributor": "20th Century Fox",
    "year": 2009,
    "amount": "$2,787,965,087",
    "img": {
      "src": "media/avatar.jpg",
      "alt": "avatar"
    },
    "ranking": 1
  },
  {
    "id": 2,
    "title": "Titanic",
    "distributor": "20th Century Fox",
    "year": 1997,
    "amount": "$2,187,463,944",
    "img": {
      "src": "media/titanic.jpg",
      "alt": "titanic"
    },
    "ranking": 2
  },
  {
    "id": 3,
    "title": "Star Wars: The Force Awakens",
    "distributor": "Walt Disney Studios Motion Pictures",
    "year": 2015,
    "amount": "$2,068,223,624",
    "img": {
      "src": "media/star_wars_the_force_awakens.jpg",
      "alt": "star_wars_the_force_awakens"
    },
    "ranking": 3
  },
  {
    "id": 4,
    "title": "Avengers: Infinity War",
    "distributor": "Walt Disney Studios Motion Pictures",
    "year": 2018,
    "amount": "$2,048,359,754",
    "img": {
      "src": "media/avengers_infinity_war.jpg",
      "alt": "avengers_infinity_war"
    },
    "ranking": 4
  },
  {
    "id": 5,
    "title": "Jurassic World",
    "distributor": "Universal Pictures",
    "year": 2015,
    "amount": "$1,671,713,208",
    "img": {
      "src": "media/jurassic_world.jpg",
      "alt": "jurassic_world"
    },
    "ranking": 5
  }
]
class List extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      loading: true,
    };
  }

  async componentDidMount() {
    
    const movies = await fetch('../../assets/data.json');
    const moviesJSON = await movies.json();
  
    console.log(moviesJSON);
    if (moviesJSON) {
      this.setState({
        data: moviesJSON,
        loading: false,
      });
    }
  }

  render() {
    const { data, loading } = this.state;

    if (loading) {
      return <div>Loading...</div>;
    }

    return (
      <div className='row'>
        {data.map(movie => (
          <div key={movie.id} className='col-sm-2'>
            <Card movie={movie} />
          </div>
        ))}
      </div>
    );
  }
}

export default List;

3 个答案:

答案 0 :(得分:2)

您获取 json 的 URL 几乎肯定不会返回您认为的 json 文件,而是提供一个 HTML 错误页面(以 < 开头)。在提取后添加一个 console.log(movies) 以对此进行调试。

此外,您拥有的 URL 是路径(包括 ..),而不是 URL。问题是您的网络服务器在哪里提供该文件。

答案 1 :(得分:1)

const movies = await fetch('../../assets/data.json');

您应该在文件顶部导入 json,而不是这样做

import movies from '../../assets/data.json';

然后就可以在 ComponentDidMount 中访问 movies。既然是本地数据,就不用做api调用了

答案 2 :(得分:1)

当 fetch 未返回有效的 json 数据时,您会收到此错误。这是导致错误的行。

const moviesJSON = await movies.json();

您可以尝试将 movies.json() 更改为 movies.text() 并登录以查看数据。

const moviesJSON = await movies.text();
console.log((moviesJSON));