从状态检索的数据不会显示在FlatList中

时间:2019-08-28 16:58:15

标签: reactjs react-native firebase-realtime-database

我在将数据从Firebase渲染到FlatList组件时遇到问题。

仅当我将数组硬编码到data属性中时,我才能成功呈现FlatList。当我通过状态清单传递数据时,FlatList不会呈现任何内容。

任何帮助将不胜感激。

loadBooks = () => {
    this.setState({
    refreshing: true,
    book_feed: []
    });

    var that = this;

    database
        .ref('books')
        .once('value')
        .then(function(snapshot) {
        const exists = snapshot.val();        
        if (exists) data = snapshot.val();
        for (var book in data) {
            var bookObj = data[book];
            that.state.book_feed.push({
                id: book,
                name: bookObj.name,
                url: bookObj.image,
                price: bookObj.price
            });
        }        
        })
        .catch(error => console.log(error));

    that.setState({
        refreshing: false,
        loading: false
    });
};

loadNew = () => {
    this.loadBooks();
};

componentDidMount() {
    this.loadNew();    
}

render() {
    <View>
        {this.state.loading == true ? (
            <Text>Loading...</Text>) : (
        <FlatList
            refreshing={this.state.refreshing}
            onRefresh={this.loadNew}
            data={this.state.book_feed}
            renderItem={({ item }) => 
            <Text style={{ flex: 1 }}>{item.name}</Text>}
        />)}      
    </View>
}

1 个答案:

答案 0 :(得分:1)

您直接在更改 GeometryReader { reader in ScrollView() { Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") .lineLimit(nil) .frame(width: reader.size.width, height: reader.size.height) } } ,这是错误的代码习惯。

正确的代码如下:

state