繁体   English   中英

为什么我收到错误:类型错误:无法读取未定义的属性“地图”?

[英]Why am I getting an error : TypeError: Cannot read property 'map' of undefined?

得到一个错误:类型错误:无法读取未定义的属性“地图”。 在重新加载页面之前,它工作正常。 但是当我重新加载页面时出现错误。 我想从数组中获取对象值。

在此处输入图片说明

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.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将是 undefined`。 要解决此问题,您可以尝试以下代码:

class Menu extends Component {

  componentDidMount() {
    this.props.fetchData();
  }

  render() {
    return (
      <View>
        <Text>{this.props.data.data.categories.map(nm => nm.name)}</Text>
      </View>
    );
  }
}

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

我以前遇到过这个问题,我通过图像数组映射解决了它,因为获取数据是异步的,似乎在渲染开始时数据不可用并且映射时出错的原因,您应该处理您的应用程序并防止在数据之前渲染设置为 state ,因此实现检查器以查看数据在 state 中完全可用,然后让 render ,这是唯一的解决方案,没有别的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM