首页 > 解决方案 > JSON 解析错误:无法识别的令牌'<' - 在 React Native 中

问题描述

我在 React Native 中遇到问题。消息是这样的JSON Parse error: Unrecognized token '<'。当我获取时会发生这种情况。

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

export default class FetchExample extends React.Component {

  constructor(props) {
    super(props);
    this.state ={ isLoading: true}
  }

  componentDidMount() {
    return fetch("http://10.0.3.2:80/api/user", {
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json, text/plain, */*"
        },
        method: 'GET'
    }).then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.user,
        }, function(){

        });

      })
      .catch((error) => {
        console.error(error);
      });
  }
 
  render() {
    if(this.state.isLoading) {
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.email}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}

这是我的 JSON。我在 Laravel 中构建。

return->response()->json(['user', $user])
["user",[{"id":1,"name":"","email":"danang@gmail.com","email_verified_at":null,"created_at":null,"updated_at":null}]]

标签: react-native

解决方案


我认为你的 json 格式不正确请试试这个 json

     {
     "user":[{
     "id":1,
     "name":"",
     "email":"danang@gmail.com",
     "email_verified_at":null,
     "created_at":null,
     "updated_at":null}]}

推荐阅读