【发布时间】: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