You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native JS致命解析错误:意外令牌,代码末尾报错求助

问题排查与修复方案

嘿,我帮你揪出代码里的几个问题啦,咱们一个个来看:

  • 生命周期方法拼写错误:你写的componentWilMount少了一个字母l,正确写法是componentWillMount。这个拼写失误会让React识别不到这个生命周期方法,里面的请求逻辑自然不会执行,这大概率是你报错的核心原因之一。
  • API响应解析错误:你调用的音乐专辑API返回的直接就是一个专辑数组,并不是嵌套在data字段里的对象。所以你不需要取response.data,直接用拿到的response就行。
  • 缺失完整的render方法:你的代码最后是re...,明显是render方法没写完——React类组件必须要有render方法来返回JSX结构,不然会直接抛出语法错误。

修复后的完整代码

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class AlbumList extends Component {
  state = { albums: [] };

  // 修正拼写:componentWillMount
  componentWillMount() {
    fetch('https://rallycoding.herokuapp.com/api/music_albums')
      .then(response => response.json())
      // 直接使用返回的数组,无需取data字段
      .then(albums => this.setState({ albums }));
  }

  // 补充完整的render方法,渲染专辑列表
  render() {
    const albumList = this.state.albums.map(album => (
      <View key={album.id || album.title} style={{ marginVertical: 8 }}>
        <Text style={{ fontSize: 18, fontWeight: 'bold' }}>{album.title}</Text>
        <Text style={{ fontSize: 14 }}>by {album.artist}</Text>
      </View>
    ));

    return <View style={{ padding: 16 }}>{albumList}</View>;
  }
}

export default AlbumList;

额外小建议

另外要注意,componentWillMount在React 16.3+版本里已经被标记为过时啦,如果你的项目用的是较新的React版本,更推荐用componentDidMount来替代,它的执行时机更稳定,还能避免生命周期相关的警告:

// 替换原来的componentWillMount
componentDidMount() {
  fetch('https://rallycoding.herokuapp.com/api/music_albums')
    .then(response => response.json())
    .then(albums => this.setState({ albums }));
}

内容的提问来源于stack exchange,提问作者firstofthree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:05:56