使用 setState 时不会加载图像 URI [英] Image URI won't load when using setState
问题描述
即使我在控制台记录 URI 值,我的 <Image/>
仍然是空白的.
My <Image/>
remains blank even though I am console logging the URI value.
我从 API 获取 URI.我得到的 URI 也绝对是 https.
I am getting the URI from an API. The URI I'm getting is definitely https as well.
我的代码如下所示:
constructor(props){
super(props)
this.state = {
img: ''
}
}
componentDidMount() {
this.getImage(this.props.id)
}
getImage(id){
_this = this;
fetch(`someURL${userId}`, {
method: 'get',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
})
.then(response => response.json())
.then((responseJson) => {
_this.setState({
img: responseJson.pic_url,
});
});
}
render() {
if (this.state.img) {
return (
<Image
resizeMode="cover"
style={{height: 50, width: 50}}
source={{uri: this.state.img}}
/>
}
return(
<View/>
)
}
如果我像 source={{uri: 'https://my-link'}}
一样直接将链接放入 URI 中,它就可以工作.我需要能够使用状态,尽管 b/c 链接来自我的 api.
If I just put the link into the URI directly like source={{uri: 'https://my-link'}}
it works. I need to be able to use state though b/c the link is coming from my api.
推荐答案
我创建了一个 小吃展 使用以下代码:
I've created a snack expo with the following code:
import React, { Component } from 'react';
import { Image, Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
constructor() {
super();
this.state = {
imageUri: '',
};
}
componentWillMount() {
const _this = this
fetch('https://jsonplaceholder.typicode.com/photos/1')
.then(res => res.json())
.then(json => {
_this.setState({
imageUri: json.url.replace('http', 'https')
});
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Image Test!
</Text>
{
this.state.imageUri ? (
<Image
resizeMode="cover"
source={{uri: this.state.imageUri}}
style={{height: 200, width: 200}}
/>
) : null
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
而且它工作得很好.我从 API 获得的 url 是 http,所以我不得不将其更改为 https,否则它将无法正常工作.也许那是你的问题.
And it works just fine. The url that I get from the API is http, so I had to change it to https because it wouldn't work otherwise. Maybe that is your problem.
这篇关于使用 setState 时不会加载图像 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!