【发布时间】:2016-12-03 18:56:46
【问题描述】:
我是使用Redux 的react native 的新手,我正在开发一个listView,显示一些contacts 和firstName 和lastName。当我按下一行时,该行应该改变它的样式。
渲染初始化很好,但是当我按下该行时,我得到了这个错误:
undefined is not an object (evaluating 'this.props.contact.firstName')
我认为我传递给datasource 的对象是空的,但我真的不知道如何绕过它。我尝试在加载 datasource 时向状态为 true 添加一个布尔值,但它不起作用。
这是我的代码:
class ParticipantsListComponent extends Component<StateProps, { dataSource: ListViewDataSource }> {
constructor(props: StateProps) {
super(props);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 != r2 });
this.state = {
dataSource: ds.cloneWithRows(this.props.participants)
};
}
componentWillReceiveProps(nextProps: StateProps) {
if (nextProps.participants !== this.props.participants) {
this.setState({
dataSource: this.state.dataSource.cloneWithRowsAndSections(nextProps.participants)
});
}
}
_renderRow = (entry: { contact: Contact, selected: boolean }, section: number, row: number) => {
return (
<ParticipantsListItem
contact={entry.contact}
selected={entry.selected} />
);
}
render() {
return (
<View style={styles.viewStyles}>
<TextInput style={styles.textInputStyles} />
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
</View>
);
}
}
export const ParticipantsList: ComponentClass<void> = connect(
(state: StoreState, ownProps: void): StateProps => ({
participants: state.contacts.contacts.map(contact =>
({
contact,
selected: state.newTopic.participants.contains(contact.id)
})).toArray()
}),
dispatch => ({})
)(ParticipantsListComponent) as ComponentClass<any>;
基本上我需要找到一种方法来确保我传递给dataSource 的数据不是未定义的。如果有人知道解决方案,我会很高兴听到它。
您会在下面找到ParticipantListItemComponent 的代码:
class ParticipantsListItemComponent extends Component<OwnProps & DipatchProps, void> {
render() {
return (
<TouchableOpacity onPress={() => this.props.onPress(this.props.contact.id)} style={styles.container} >
<Text style={styles.name}>{!this.props.selected ? this.props.contact.firstName : ''} {this.props.contact.lastName}</Text>
<View style={{ flex: 1 }} />
</TouchableOpacity>
);
}
}
export const ParticipantsListItem: ComponentClass<OwnProps> = connect(
(state: void, ownProps: void): {} => ({}),
dispatch => ({
onPress: (id: string) => dispatch(toggleParticipant(id))
})
)(ParticipantsListItemComponent);
【问题讨论】:
-
你能告诉我们你的
connect函数吗? -
是的,当然,我什至没有注意到我忘记了它
-
我认为您的问题出在
ParticipantsListItem组件中,因为初始渲染正在工作。很抱歉再次询问,但是,您介意发布该组件吗? -
没问题,我马上做
-
您在
componentWillReceiveProps方法中使用的是cloneWithRowsAndSections而不是cloneWithRows?
标签: listview react-native redux datasource react-redux