[英]Why am I getting an error : TypeError: Cannot read property 'map' of undefined?
Getting an error: TypeError: Cannot read property 'map' of undefined.得到一个错误:类型错误:无法读取未定义的属性“地图”。 Before reloading the page it's work fine.在重新加载页面之前,它工作正常。 But when I'm reloading the page getting an error.但是当我重新加载页面时出现错误。 I want to get object values from array.我想从数组中获取对象值。
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {fetchData} from '../../actions/fetchData';
class Menu extends Component {
componentDidMount() {
this.props.fetchData();
}
render() {
const {data, isFetching} = this.props.data;
if (isFetching) {
return (
<View>
<ActivityIndicator size={'large'} />
</View>
);
} else {
return (
<View
style={{
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>
{data.categories.map(nm => nm.name)}
{/* {console.log("data",data.categories.map(nm => nm.name))} */}
</Text>
</View>
);
}
}
}
function mapStateToProps(state) {
return {
data: state.data,
};
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({fetchData}, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Menu);
I'm not a react-native
developer, but have working small experience on react
.我不是react-native
开发人员,但在react
有一些工作经验。 Here what I can understand as given below:在这里,我可以理解如下:
this.state = {
data: this.props.data,
};
In above code in constructor
, first initialize with state.data
, when class instance is called and it will be undefined
.在上面的constructor
代码中,首先使用state.data
初始化,当类实例被调用时,它将是undefined
。 Because when first class is called, this.props.data
is undefined
.因为当第一类被调用时, this.props.data
是undefined
。
componentDidMount() {
this.props.fetchData();
}
After constructor
's task complete, above code will be executed and it's data is shown in console.log
. constructor
的任务完成后,上面的代码将被执行,其数据显示在console.log
。 But returned data is never assign to any variable.但是返回的数据永远不会分配给任何变量。 That means, after fetching data, this.state.data
still is undefined
.这意味着,在获取数据后, this.state.data
仍然是undefined
。
so when comes to executing <Text>{this.state.data.data.categories.map(nm => nm.name)}</Text>
, this.state.data
will be undefined`.所以当执行<Text>{this.state.data.data.categories.map(nm => nm.name)}</Text>
, this.state.data
将是 undefined`。 To solve this problem, you can try following code:要解决此问题,您可以尝试以下代码:
class Menu extends Component {
componentDidMount() {
this.props.fetchData();
}
render() {
return (
<View>
<Text>{this.props.data.data.categories.map(nm => nm.name)}</Text>
</View>
);
}
}
And one last thing, I strongly recommend that, you learn react development life-cycle.最后一件事,我强烈建议您学习 React 开发生命周期。 Thanks谢谢
我以前遇到过这个问题,我通过图像数组映射解决了它,因为获取数据是异步的,似乎在渲染开始时数据不可用并且映射时出错的原因,您应该处理您的应用程序并防止在数据之前渲染设置为 state ,因此实现检查器以查看数据在 state 中完全可用,然后让 render ,这是唯一的解决方案,没有别的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.