Search code examples
reactjslistviewreact-nativereduxreact-lifecycle

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


I'm currently learning React Native. I want to write a ListView. The tutorial I'm following uses the deprecated method componentWillMount, which is now called UNSAFE_componentWillMount. I googled an people said one should replace that method with componentDidMount. My problem is when I add this method to my code, the app breaks.

Here is the code:

/* @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);

And here is the error message that I get TypeError: Cannot read property 'rowIdentities' of undefined. Which method am I supposed to use here, or how can I fix this?


Solution

  • I solved the problem by using a FlatList instead. I found out that ListView is deprecated :) Here is the code I ended up using:

    /* @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);