0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • This is because componentDidMount runs after first render. So, in the first render if there is no data that holds rowIdentites you get this error. You need to render your component conditionally. Where does rowIdentites come from? dataSource? – devserkan Jun 26 '18 at 21:00

1 Answers1

0

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);
J. Hesters
  • 13,117
  • 31
  • 133
  • 249