我使用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不是一个对象(评估'this.props.item.id') ...我收到的json有6个项目,我得到它正确(从console.log检查)。如果我将一些静态传递给ItemView ...说item ='product'然后它被渲染了6次......所以一切似乎都运行良好,但由于某种原因它不会得到对象
答案 0 :(得分:0)
似乎你不使用propTypes。在RN中,如果从外部导入组件并将数据发送到RN,则可以使用propTypes。
您可以使用npm安装。
npm install --save prop-types
之后,在这里尝试这个ITEMVIEW,它应该工作。如果没有,这意味着您的数据存在问题。因此,请在调用组件之前检查数据。
import React from 'react';
import PropTypes from 'prop-types';
import { View, Text } from 'react-native';
class ItemOverView extends React.Component {
constructor(props) {
super(props);
}
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,
}
};
ItemOverView.propTypes = {
item: PropTypes.object,
};
ItemOverView.defaultProps = {
item: null,
};
export { ItemOverView };