首页 > 解决方案 > 无法从 react-native 中的 JSON API 获取图像

问题描述

我是 react-native 的新手,我正在尝试从 JSON API 获取图像 url。当我运行我的代码时,出现错误“源未定义”。所以我只想知道如何从 JSON 获取我的图像 url API。我能够获取 URL 的响应,请检查我的代码。

    async componentDidMount() {
    const DEMO_TOKEN = await AsyncStorage.getItem('isLoggedIn');
        const url11 = 'http://104.197.28.169:3000/userProfile';
        fetch(url11,{
            method: 'GET',
            headers: {
                Authorization: 'Bearer ' + DEMO_TOKEN,
            },
            //Request Type
        })
            .then(response => response.json())
            .then(responseJson => {
                console.log('UserProresponse', responseJson)
                this.setState({
                    dataSource : responseJson,
                    isLoading: false,
                });
            })
            .catch(error => console.log(error));
    }

  <View style={styles.imageView}>
                            <Image style={styles.logoImg}
                                source={require(this.state.dataSource.data.photograph)}>
                              </Image>
   </ VIew>

我收到了这个 console.log 响应。在这里我可以得到“firstName”,但我无法从这个响应中得到“照片”。请检查。

 {
 "message": "user profile",
"data": {
    "id": 1,       
    "firstName": "Mohd",
    "lastName": "Akram",
    "dateOfBirth": "1995-08-25",
    "gender": "male",
    "maritalStatus": "unmarried",       
    "photograph": "images/2020-04-28T10-37-21.149Zdutch.png",        
    "userId": 2,
 },
"status": 1
}

标签: react-native

解决方案


你应该使用uri: if get from internet 或 server。

例子 :

<Image source={{uri: this.state.dataSource.data.photograph}} style={{width:200, height: 200}} />

并且不要忘记定义图像的大小(宽度和高度),如果您从 React Native 中的 rest API 获取图像


推荐阅读