React Native:如何使用 ListView 处理生命周期方法的弃用?

React Native: How to handle the deprecation of the lifecycle methods with ListView?

我目前正在学习 React Native。我想写一个ListView。我正在学习的教程使用已弃用的方法 componentWillMount,现在称为 UNSAFE_componentWillMount。我用谷歌搜索了一个人说应该用 componentDidMount 替换那个方法。我的问题是当我将此方法添加到我的代码时,应用程序中断了。

代码如下:

/* @flow */

import React, { Component } from "react";
import { ListView } from "react-native";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import ListItem from "./ListItem";

class LibraryList extends Component {
  componentDidMount = () => {
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });

    this.dataSource = ds.cloneWithRows(this.props.libraries);
  };

  renderRow = library => <ListItem library={library} />;

  render() {
    return <ListView dataSource={this.dataSource} renderRow={this.renderRow} />;
  }
}

LibraryList.propTypes = {
  libraries: PropTypes.array
};

const mapStateToProps = state => {
  return { libraries: state.libraries };
};

export default connect(mapStateToProps)(LibraryList);

这是我收到的错误消息 TypeError: Cannot read property 'rowIdentities' of undefined。我应该在这里使用哪种方法,或者我该如何解决这个问题?

我使用 FlatList 解决了这个问题。我发现 ListView 已被弃用 :) 这是我最终使用的代码:

/* @flow */

import React, { Component } from "react";
import { FlatList } from "react-native";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import ListItem from "./ListItem";

class LibraryList extends Component {
  state = {
    dataSource: []
  };
  componentDidMount = () => {
    this.setState({ dataSource: this.props.libraries });
  };

  renderRow = ({ item: library }) => <ListItem library={library} />;

  render() {
    return (
      <FlatList
        data={this.state.dataSource}
        renderItem={this.renderRow}
        keyExtractor={item => item.id.toString()}
      />
    );
  }
}

LibraryList.propTypes = {
  libraries: PropTypes.array
};

const mapStateToProps = state => {
  return { libraries: state.libraries };
};

export default connect(mapStateToProps)(LibraryList);