So, I was working with React Native and found a very silly problem which I can't seem to get my head around. I have declared an array of objects (storeVar here) with some hardcoded value. When I try to loop through it using the javascript map function I get only the value only at the first index. The code is below -
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) }
});
}
Only Hello is displayed and not the text Awesome. Any help would be greatly appreciated.
答案 0 :(得分:0)
请勿使用index-1
,请使用
JSON.stringify(storeVar[index].n, null, 4));
该索引将从0
开始,因此-1
的{{1}}将导致0
,并且无法访问 -1th -1
的元素,当索引变为array
且1
时,它将1 - 1
打印Hello(0
索引元素)。