我目前正在开发React Native移动应用程序。
我想在FlatList中显示数据库中的数据,但到目前为止出现了两个问题:
如果尚未提取数据,则无法mapStateToProps
假设尚未显示数据,则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);```
最佳答案
当数据为null时(如果您希望接收一个数组),您可以(并且应该)将所有内容默认为空数组:
_.map(state.bookshelf?.booklist || [], (val, uid) => ...)
注意,
?
仅根据babel
编译器的版本可用。如果您使用的是最新版本的React Native,它应该可以工作。如果没有,您将不得不做更多的检查,例如state.bookshelf && state.bookshelft.booklist || []
。<FlatList
data={this.props.booklist || []}
...
/>
如果收到的数据可能是
null
,则应始终提供默认值或有条件地呈现。关于javascript - 在React Native中使用异步组件实现Redux,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61528087/