2017-06-12 48 views
0

所以,我正在與React Native合作,發現了一個非常愚蠢的問題,我似乎無法擺脫困境。我已經用一些硬編碼值聲明瞭一個對象數組(這裏是storeVar)。當我嘗試使用JavaScript映射函數來循環使用它時,我只在第一個索引處獲得值。代碼如下 -Javascript |反應原生地圖功能無法正常工作

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    TextInput, 
    ScrollView, 
    AsyncStorage, 
    TouchableOpacity 
} from 'react-native'; 

import Note from './note.js' 

// ------------------------------------------------------------------------- 


const storeVar = [ 
    { 
     'd' : '', 
     'n' : 'Hello' 
    }, 
    { 
     'd' : '', 
     'n' : 'Awesome' 
    }, 
]; 

export default class reactNativePractise extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     noteArray : [ 
      { 
       'date' : '', 
       'note' : '' 
      } 
     ], 
    }; 
} 

componentDidMount() { this.onLoad(); } 

onLoad = async()=> { 
    storeVar.map(async(value, index) => { 
     try { 
      var d = new Date(); 
      // const storedVal = [await AsyncStorage.getItem(storeVar[index].n)]; 
      alert("Key is : " + JSON.stringify(storeVar[index-1].n, null, 4)); 

      // this.state.noteArray.push({date :d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate(), note : storedVal[index]}); 
     } 
     catch(error) { alert('Error' + error) } 
    }); 
} 

只顯示Hello,不顯示文字Awesome。任何幫助將不勝感激。

回答

0

不要使用index-1,使用

JSON.stringify(storeVar[index].n, null, 4)); 

該指數將從0開始,這樣做的0-1將導致對-1,並且它將無法訪問array,當-1th索引變爲1,1 - 1將爲0,那時它的打印Hello(0th索引元素)。

+0

現在問題就解決了! –