javascript - 为什么我收到错误:TypeError:无法读取未定义的属性“地图”?
问题描述
收到错误:TypeError:无法读取未定义的属性“地图”。在重新加载页面之前它工作正常。但是当我重新加载页面时出现错误。我想从数组中获取对象值。
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);
解决方案
我不是react-native
开发人员,但在react
. 这里我可以理解如下:
this.state = {
data: this.props.data,
};
在上面的代码中constructor
,首先用 初始化state.data
,当类实例被调用时,它将是undefined
。因为当第一堂课被调用时,this.props.data
是undefined
。
componentDidMount() {
this.props.fetchData();
}
任务完成后constructor
,将执行上述代码,其数据显示在 中console.log
。但是返回的数据永远不会分配给任何变量。这意味着,在获取数据之后,this.state.data
仍然是undefined
.
所以在执行时<Text>{this.state.data.data.categories.map(nm => nm.name)}</Text>
,this.state.data
将是未定义的。要解决此问题,您可以尝试以下代码:
class Menu extends Component {
componentDidMount() {
this.props.fetchData();
}
render() {
return (
<View>
<Text>{this.props.data.data.categories.map(nm => nm.name)}</Text>
</View>
);
}
}
最后一件事,我强烈建议你学习反应开发生命周期。谢谢
推荐阅读
- android - 如何在没有 getExternalStorageDirectory() 的情况下从 Android 上的根目录读取文件?
- nuodb - Centos:启动失败 LSB:启动 NuoDB Admin
- r - 运行多行代码但在 R 中出现错误(来自 RStudio)?
- javascript - 在 google sheet 脚本中声明 const 的替代方法
- python - 气流initdb上的sql炼金术连接终止
- dart - 在这种情况下如何更改变量的值?
- react-native - 我可以在我的应用程序中触发或运行本地推送通知吗?
- r - 映射列表并创建训练和测试拆分
- sql - 将表格格式更改为透视
- regex - 有没有一种 Ruby 方法可以替换字符串的最后四位数字,不包括空格?