React Native:尝试从https://cataas.com api获取图像时出现错误

时间:2018-11-22 15:45:46

标签: react-native fetch

我收到了SyntaxError:Json Parse错误:JSON Parse错误:无法识别的令牌'<'

我正在使用https://cataas.com API来响应本机应用程序,我的任务是生成随机小猫图像的列表。我尝试使用提取方法,但也收到错误sorce.uri不应为空字符串。我该如何解决这个问题?

这是我的代码:

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;

2 个答案:

答案 0 :(得分:0)

您的代码中有错字

url替换为docsuri

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

答案 1 :(得分:0)

您不必手动调用此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系统,我稍后可能会进行调查。