【问题标题】:React Native: How to handle the deprecation of the lifecycle methods with ListView?React Native:如何使用 ListView 处理生命周期方法的弃用?
【发布时间】:2018-06-26 20:51:32
【问题描述】:

我目前正在学习 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。我应该在这里使用哪种方法,或者我该如何解决这个问题?

【问题讨论】:

  • 这是因为 componentDidMount 在第一次渲染后运行。因此,在第一次渲染中,如果没有包含 rowIdentites 的数据,则会出现此错误。您需要有条件地渲染您的组件。 rowIdentites 来自哪里?数据源?

标签: reactjs listview react-native redux react-lifecycle


【解决方案1】:

我改用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多