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.
Don't use index-1
, use
JSON.stringify(storeVar[index].n, null, 4));
that index will start from 0
, so doing -1
of 0
will result to -1
, and it will fail to access -1th element of array
, when index becomes 1
and 1 - 1
will be 0
at that time its printing the Hello ( 0th
index element).
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.