简体   繁体   中英

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 . 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 . Because when first class is called, this.props.data is undefined .

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

After constructor 's task complete, above code will be executed and it's data is shown in console.log . But returned data is never assign to any variable. That means, after fetching data, this.state.data still is undefined .

so when comes to executing <Text>{this.state.data.data.categories.map(nm => nm.name)}</Text> , this.state.data will be 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. Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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