【发布时间】:2020-05-08 18:39:14
【问题描述】:
我正在尝试根据用户选择的内容打印一组图像并将它们打印在 2 列上,但我在这样做时遇到了问题
import React, { Component } from 'react';
import {View, FlatList} from 'react-native';
import {f, auth, database} from '../../config/firebase';
import {SearchBar} from "react-native-elements";
import {ArtObjectCard} from "../components/ArtObjectCard";
export default class ExhibitionDetailScreen extends Component{
static navigationOptions = {
headerShown: false,
};
constructor(props)
{
super(props);
this.state = {
exhibit: props.navigation.state.params.exhibit,
objectIds: [],
objects: []
};
}
getObject = (objId) => {
const ref = database.ref('object').child(objId);
ref.once('value').then((snapshot) => {
let object = snapshot.val();
object["id"] = objId;
this.state.objects.push(object);
});
}
getData = () => {
database.ref(`exhibition_object/${this.state.exhibit.id}`).once('value')
.then((snapshot) => {
this.setState({
objectIds: Object.keys(snapshot.val())
})
for( let i = 0;i < this.state.objectIds.length;i++ )
{
// Create a new array based on current state:
let arr = [...this.state.objects];
// Add item to it
arr.push(this.getObject(this.state.objectIds[i]));
// Set state
this.setState({ objects: arr });
}
});
}
componentDidMount () {
this.getData()
}
keyExtractor = (item, index) => {
return index.toString();
}
renderItem = ({item, index}) => {
if (!item) {
return null
}
return (
<View>
<ArtObjectCard
title={item.title}
image={{uri: item.image}}
onClickButton={()=>{this._onPressItem(item)}}
/>
</View>
);
}
render(){
const { search } = this.state;
return (
<View style={{flex: 1}}>
<SearchBar
placeholder="Type something here...."
onChangeText={this.updateSearch}
value={search}
/>
<FlatList
data={this.state.objects}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
numColumns={2}
/>
</View>
);
}
}
我正在使用 firebase 来获取图像。 当我有 3 个项目的数组时,就会出现这个问题
当我有 2 个元素的 aray 时没有问题
我有这个问题是因为数据没有时间加载,还是我该如何解决这个问题?
编辑 1: 我试过了,但它仍然不适合我
renderItem = ({item, index}) => {
return (
<View>
<ArtObjectCard
title={item?item.title:""}
image={{uri:item.image}}
onClickButton={()=>{this._onPressItem(item)}}
/>
</View>
);
}
ArtObjectCard 类
import React, { Component } from "react";
import {
Text,
View,
Image,
Dimensions,
Platform,
ProgressViewIOS,
ProgressBarAndroid,
} from "react-native";
let screenWidth = Dimensions.get("window").width;
export class ArtObjectCard extends Component<Props> {
constructor(props) {
super(props);
}
render() {
return (
<View
style={{
height: 200,
margin: 10,
}}
>
<View
>
<Image
borderRadius={10}
source={this.props.image}
style={{
width: this.props.width ? this.props.width : screenWidth/2 - 20,
height: this.props.height ? this.props.height : 200,
resizeMode: "cover"
}}
/>
</View>
</View>
);
}
}
编辑2:
如果我替换this.setState({ objects: arr });这一行
到
this.setState({ arr });
3 个对象将被正确打印,但当有 2 个对象时出现空白屏幕
【问题讨论】:
标签: javascript reactjs firebase react-native react-native-flatlist