我目前正在开发一个React本地移动应用程序。
我想在FlatList中显示来自数据库的数据,但到目前为止出现了两个问题:
如果数据尚未被获取,则
我已经尝试创建一个加载支柱,它将在组件挂载时立即被设置为true,并将“取消”需要数据的函数;但是,到目前为止,这还没有起作用。
import React, { Component } from "react";
import { View, Text, Button, FlatList } from "react-native";
import { connect } from "react-redux";
import { Spinner } from "../../common";
import { booksFetch } from "../../actions/BookshelfActions";
class BookshelfList extends Component {
componentDidMount() {
this.props.booksFetch(); // Gets the data from the website
}
addBookScreen = () => {
this.props.navigation.navigate("bookshelfadd");
};
renderRow(book) {
return (
<View>
<Text>{book.book_name}</Text>
</View>
);
}
renderList() {
if (this.props.loading) {
console.log("loading");
return <Spinner />;
}
return (
<FlatList // Shows the data on the screen. Will crash if there is no data
data={this.props.booklist}
renderItem={() => this.renderRow()}
keyExtractor={(book) => book.uid}
/>
);
}
render() {
return (
<View>
{this.renderList()}
<Button onPress={this.addBookScreen} title="Add Book" />
</View>
);
}
}
const mapStateToProps = (state) => {
if (!this.props.loading) {
const user_books = _.map(state.bookshelf.booklist, (val, uid) => { // Maps the data to the state. Will crash if there is no data
return { ...val, uid };
});
}
return {
booklist: user_books || null,
loading: state.bookshelf.loading,
};
};
export default connect(mapStateToProps, { booksFetch })(BookshelfList);```发布于 2020-04-30 16:31:04
当数据为null时,您可以(而且应该)默认为空数组(如果您期望接收一个数组):
_.map(state.bookshelf?.booklist || [], (val, uid) => ...)注意,?只根据babel编译器的版本而可用。如果您使用的是Reacti原住民的最新版本,那么它应该可以工作。如果没有,您将不得不做一些更多的检查,如state.bookshelf && state.bookshelft.booklist || []。
<FlatList
data={this.props.booklist || []}
...
/>如果收到的数据可能是null,则应始终提供默认值或有条件呈现。
https://stackoverflow.com/questions/61528087
复制相似问题