[英]Redux with async components in React Native
I am currently developing a React Native mobile application.我目前正在开发一个 React Native 移动应用程序。
I want to show the data from a database in a FlatList but two problems have come up so far:我想在 FlatList 中显示数据库中的数据,但到目前为止出现了两个问题:
I have tried to create a loading prop that will be sent set as true as soon as the component is mounting and will 'unblock' the functions that require the data;我试图创建一个加载道具,该道具将在组件安装后立即发送设置为真,并将“解锁”需要数据的功能; however this has not worked so far.
然而,到目前为止这还没有奏效。
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);```
You can (and should) default everything to empty arrays when the data is null (if you are expecting to receive an array):当数据为 null 时(如果您希望收到一个数组),您可以(并且应该)将所有内容默认为空 arrays:
_.map(state.bookshelf?.booklist || [], (val, uid) => ...)
Note, ?
注意,
?
is only available depending on the version of the babel
compiler.仅根据
babel
编译器的版本可用。 If you're using the latest version of React Native, it should work.如果您使用的是最新版本的 React Native,它应该可以工作。 If not, you'll have to do some more checks such as
state.bookshelf && state.bookshelft.booklist || []
如果没有,您将不得不进行更多检查,例如
state.bookshelf && state.bookshelft.booklist || []
state.bookshelf && state.bookshelft.booklist || []
. state.bookshelf && state.bookshelft.booklist || []
。
<FlatList
data={this.props.booklist || []}
...
/>
You should always provide a default value or conditionally render if the data you receive might be null
.如果您收到的数据可能是
null
,则应始终提供默认值或有条件地呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.