簡體   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