【问题标题】:React Native: I am getting error while trying to get image from https://cataas.com apiReact Native:尝试从 https://cataas.com api 获取图像时出现错误
【发布时间】:2018-11-22 15:45:46
【问题描述】:

我收到 SyntaxError: Json Parse error: JSON Parse error: Unrecognized token '

我正在将https://cataas.com api 用于反应原生应用程序,我的任务是生成随机小猫图像列表。我尝试使用 fetch 方法,但我也得到错误 sorce.uri should not be an empty string。我该如何解决这个问题?

这是我的代码:

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

class App extends Component {
 state = {
      photos: '',
    }


componentDidMount() {
   fetch('https://cataas.com/cat?width=100')
     .then(res => res.json())
     .then(data => {
       this.setState({
           photos: data
         })
         .catch(err => {
           console.log('error', err);
           alert(err)
         })
     })
}


render() {
    console.log(this.state.photos)
    return (
      <View style={styles.container}>
        <Image 
          source={{url: this.state.photos}} 
          style={{height: 100, width: 100}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  }
});

export default App;

【问题讨论】:

    标签: react-native fetch


    【解决方案1】:

    你的代码有错别字

    url 替换为uri,如docs 中所示

    <Image 
       source={{uri: this.state.photos}} 
       style={{height: 100, width: 100}}
    />
    

    【讨论】:

    • 谢谢!现在它说 sourse.uri 不应该是一个空字符串。嗯,这是否意味着它从 api 或其他东西获取 html 数据?我不知道这是否是从 api 获取图像的正确方法。
    • 你可以在你的状态下设置默认的图片字符串url而不是空字符串
    【解决方案2】:

    你不必手动调用这个api,你可以直接使用Image组件中的链接:

    <Image 
      source={{uri: "https://picsum.photos/100/100"}} 
      style={{height: 100, width: 100}}
    />
    

    编辑:

    好吧,这并不像我想象的那么容易!

    我创建了第一个基本版本:https://snack.expo.io/@sanjar/so-53434400

    与我的想法相反,它总是显示相同的图片。 这是因为 react-native 缓存系统看到相同的 url 并决定不再执行 http 请求。 然后我检查了文档,发现a way to fix this issue, but for ios only 我只需要改变:

    source={{uri: "https://source.unsplash.com/random"}}
    

    作者:

    source={{uri: "https://source.unsplash.com/random", cache: 'reload'}}
    

    应该可以在ios上运行(我现在没有mac),对于android我还不知道,我可能稍后再调查。

    【讨论】:

    • 这样一切正常,但我需要从该 api 呈现随机图片列表。
    • 如果你有一个Image列表调用一个随机的api,每个Image都会执行它自己的http请求并得到不同的图片。
    • 不幸的是,我的任务是从 api 获取它们:(
    • 谢谢!我也没有mac,所以我会在android上试试这个,希望这会奏效。再次感谢您!
    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2019-10-05
    • 2018-06-23
    • 2021-01-24
    • 2021-02-06
    • 2017-01-13
    相关资源
    最近更新 更多