首页 > 解决方案 > 为什么我收到错误: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);

标签: javascriptreact-native

解决方案


我不是react-native开发人员,但在react. 这里我可以理解如下:

this.state = {
  data: this.props.data,
};

在上面的代码中constructor,首先用 初始化state.data,当类实例被调用时,它将是undefined。因为当第一堂课被调用时,this.props.dataundefined

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>
    );
  }
}

最后一件事,我强烈建议你学习反应开发生命周期。谢谢


推荐阅读