我使用redux和axios请求创建了一个listView,一切看起来都很好....但我无法在我的渲染方法中获取对象...
这是我的代码
import React from 'react';
import { View, ListView, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import { ItemOverView } from '../../components/common';
import * as actions from '../../actions';
class AwaitingScreen extends React.Component {
static navigationOptions = {
header: null,
};
state = { loading: true };
componentWillMount() {
this.props.getAwaitingOrders();
this.createDataSource(this.props);
}
componentWillReceiveProps(nextProps) {
this.setState({ loading: false });
this.createDataSource(nextProps);
}
createDataSource(orders) {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.dataSource = ds.cloneWithRows(orders);
}
renderListView() {
if (this.state.loading) {
return (<ActivityIndicator
size='large'
color='#397af8'
/>
);
}
return (
<ListView
enableEmptySections
dataSource={this.dataSource}
renderRow={this.renderRow}
/>
);
}
renderRow = (order) => {
return (
<ItemOverView
item={order}
/>
);
}
render() {
return (
<View>
{this.renderListView()}
</View>
);
}
}
const mapStateToProps = state => {
return {
awaitingOrders: state.orders.awaitingOrders,
statusCodes: state.orders.statusCodes
};
};
export default connect(mapStateToProps, actions)(AwaitingScreen);
ItemView控件:
import React from 'react';
import { View, Text } from 'react-native';
class ItemOverView extends React.Component {
render() {
console.log(this.props.item);
return (
<View style={style.containerStyle}>
<Text>{this.props.item.id}</Text>
</View>
);
}
}
const style = {
containerStyle: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10,
}
};
export { ItemOverView };
当我运行此代码时,我收到错误 undefined is not an object (evaluating 'this.props.item.id') ...我收到的json有6个项目,我得到它正确(从console.log检查) . 如果我将一些静态传递给ItemView ...说item = 'product'然后它被渲染6次......所以一切似乎都运行良好,但由于某种原因它不会得到对象
1 回答
看来你不使用propTypes . 在RN中,如果从外部导入组件并将数据发送到其中,则可以使用propTypes .
你可以用npm安装 .
之后,在这里尝试这个ITEMVIEW,它应该工作 . 如果没有,这意味着您的数据存在问题 . 因此,在调用组件之前检查数据 .