首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有异步组件的Redux

具有异步组件的Redux
EN

Stack Overflow用户
提问于 2020-04-30 16:21:30
回答 1查看 31关注 0票数 0

我目前正在开发一个React本地移动应用程序。

我想在FlatList中显示来自数据库的数据,但到目前为止出现了两个问题:

如果数据尚未被获取,则

  1. I不能mapStateToProps,如果数据尚未显示,则FlatList组件在加载时会抛出一个错误

我已经尝试创建一个加载支柱,它将在组件挂载时立即被设置为true,并将“取消”需要数据的函数;但是,到目前为止,这还没有起作用。

代码语言:javascript
复制
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);```
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-30 16:31:04

当数据为null时,您可以(而且应该)默认为空数组(如果您期望接收一个数组):

代码语言:javascript
复制
_.map(state.bookshelf?.booklist || [], (val, uid) => ...)

注意,?只根据babel编译器的版本而可用。如果您使用的是Reacti原住民的最新版本,那么它应该可以工作。如果没有,您将不得不做一些更多的检查,如state.bookshelf && state.bookshelft.booklist || []

代码语言:javascript
复制
<FlatList
  data={this.props.booklist || []}
  ...
/>

如果收到的数据可能是null,则应始终提供默认值或有条件呈现。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61528087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档