【发布时间】:2020-05-05 00:55:19
【问题描述】:
我创建了两个函数,一个是 img(item),第二个是异步 get_customize_category_image(id),我在 img() 函数中调用第二个函数,我想在 img 变量中传递第二个函数的返回值,我做了控制台.log() 在两个函数 get_customize_category_image(id) 中返回正确的值,但在 img() 函数中没有收到正确的值 img() 函数的日志返回 {"_40":0,"_65":0,"_55": null,"_72":null} 这个数据。如何在 img() 函数中获得相同的值。
请帮我解决这个问题。
旧代码:
async get_customize_category_image(id) {
const response = await fetch(
'http://192.168.0.3:1234/get_customize_category_image?id=' + id,
);
const data = await response.json();
let img = data;
console.log(img);
return img;
}
img(item) {
if (item.customize_category) {
let img = this.get_customize_category_image(item.customize_category);
console.log(img);
return (
<Image style={styles.profilePic} source={{uri: img}} />
);
} else {
return (
<Image style={styles.profilePic} source={{uri: item.featuredImage}} />
);
}
}
新代码:
async get_customize_category_image(id) {
const response = await fetch(
'http://192.168.0.3:1234/get_customize_category_image?id=' + id,
);
const data = await response.json();
let img = data;
// console.log(img);
return String(img[0].image);
}
async img(item) {
if (item.customize_category) {
let img = await this.get_customize_category_image(
item.customize_category,
).catch(err => {
console.log(err);
});
console.log(img);
return (
<Image style={styles.profilePic} source={{uri: item.featuredImage}} />
);
} else {
return (
<Image style={styles.profilePic} source={{uri: item.featuredImage}} />
);
}
}
render() {
let img = '';
return (
<View style={styles.container}>
<HeaderIcon />
{this.state.loading && <ActivityIndicator size="large" color="cyan" />}
<FlatList
onScroll={({nativeEvent}) => {
if (this.isCloseToBottom(nativeEvent)) {
this.getMorePost();
}
}}
data={this.state.post}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (
<TouchableOpacity
style={styles.main}
onPress={() => {
this.openPost(item);
}}>
<View style={styles.row}>
<View>{this.img(item)}</View> // Hear I'm calling my img() function
<View>
<Text style={styles.title}>{item.post_title}</Text>
</View>
</View>
<Image
resizeMode="stretch"
style={styles.image}
source={{uri: item.featuredImage}}
/>
<View>
<TouchableOpacity
style={{justifyContent: 'center', padding: 10}}
onPress={() => {
Share.share({
title: item.post_title,
message: item.post_content.replace(
/<[^>]*>| /g,
' ',
),
uri: item.featuredImage,
});
}}>
<Image
source={require('../image/wlogo.png')}
style={{height: 45, width: 45, paddingLeft: 60}}
/>
</TouchableOpacity>
</View>
</TouchableOpacity>
)}
/>
</View>
);
}
}
现在错误是:
[Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
【问题讨论】:
标签: react-native