繁体   English   中英

React Native - JSON 中的意外标记 U 在位置 0

[英]React Native - Unexpected token U in JSON at position 0

从 API 向我的应用程序获取数据时出现此错误。 我检查了我的控制台,实际上我正确地获得了令牌,但出现了这个错误。 我已经用过 AsyncStorage.clear(); 在应用程序开始时

useEffect(() => {
    AsyncStorage.clear();
  });

但错误仍然出现。 即使存在该错误,我仍然可以获取数据,所以我有点忽略了它,但现在由于意外令牌,我无法更新我的数据。

首页 index.js(这是试图获取数据的文件)

import AsyncStorage from '@react-native-async-storage/async-storage';
import React, {useEffect, useState} from 'react';
import {Image, StyleSheet, Text, View} from 'react-native';
import {Button, Gap, Header} from '../../components';
import {colors, getData} from '../../utils';

export default function Home({navigation}) {
  const [profile, setProfile] = useState({
    name: '',
    email: '',
    phone_number: '',
  });
  const [data, setData] = useState([]);
  const [token, setToken] = useState('');

  useEffect(() => {
    getData('token').then(res => {
      const res_token = res;
      console.log('getting token data response at home: ', res_token);
      setToken(res_token);
    });
    fetch('https://emaillead.aturtoko.id/api/v1/profile', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer${token}`,
      },
    })
      .then(response => response.json())
      .then(json => {
        console.log('token auth: ' + token);
        setProfile({
          name: json.user.name,
          email: json.user.email,
          phone_number: json.user.phone_number,
        });
        //setData(json);
        console.log(json);
      })
      .catch(error => console.error(error));
  }, [token]);
  return (
    <View style={styles.page}>
      <Header title="User Data" />
      <Text style={styles.text}>Nama: {profile.name}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Email: {profile.email}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Nomor Telepon: {profile.phone_number}</Text>
      <Gap height={40} />
      <Button
        title="Lihat Campaign"
        onPress={() => navigation.navigate('Campaign')}
      />
    </View>
  );
}

这是控制台 + 错误消息控制台 + 错误截图

我认为问题可能出在 getData 和 fetch 之间。 您应该使用 await 或 chain with .then 方法来安排请求的顺序,否则您在获取数据时将没有 res_token。

  useEffect(() => {
    getData('token').then(res => {
      const res_token = res;
      console.log('getting token data response at home: ', res_token);
      return res_token
    }).then((res_token) => {
      // do the fetch when res_token is already got
    })
 
  }, []);

我无法弄清楚这个问题,因为我需要更多上下文,例如,您调用了代码中不存在的 getData 函数。

无论如何,我认为您应该注意以下几点:

您得到的错误不一定与您使用的“令牌”状态变量有关。 当 JavaScript 尝试解析格式错误的 JSON 字符串时,通常会抛出此错误。

例如,您可以使用以下语法在浏览器控制台中重现相同的错误。

JSON.parse("User") // VM193:1 Uncaught SyntaxError: Unexpected token U in JSON at position 0.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM