簡體   English   中英

我無法遍歷對象數組

[英]I cant iterate over an array of objects

我正在開發一個AsyncStorage Native 項目,其中所有用戶信息都使用AsyncStorage存儲在手機上,並且允許多個用戶使用同一部手機注冊。

在保存用戶信息時,我確保將它們保存為像這樣的對象數組[{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}]

現在,在

登錄頁面

我嘗試檢索所有用戶,然后使用filter檢索嘗試登錄的用戶以驗證用戶是否已注冊。 但是如果我點擊登錄按鈕,什么都不會發生,但是如果我提醒existerUser alert(existingUser); , 所有注冊用戶都會像這樣提醒[{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}]但如果我評論它出來了,當我點擊時什么都不會發生

登錄按鈕。

這是我迄今為止所做的。

import React, { Component } from 'react';
import { Text } from 'react-native';
//import { connect } from 'react-redux';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { Container, Item, Input, Icon, Button, Spinner, Label, TouchableOpacity } from 'native-base';
import { ImageBackground, Image } from "react-native";

import AsyncStorage from '@react-native-community/async-storage';
//import { onChangeTextHandler, login } from '../actions';

function filterByValue(array, string) {
    return array.filter(o =>
        Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}

export default class StudentLogin extends Component {

  constructor() {
    super();
    this.state = {
      username: '',
      password: '',
    };
  }

  getStudent = async () => {
    //function to get the value from AsyncStorage
    //let students = await AsyncStorage.getItem('student');
     const existingStudent = await AsyncStorage.getItem("student"); 

    alert(existingUser);// All the students saved records will be alerted
    //let students = existingUser.filter(es => es.username === this.state.username);// Here nothing will happen. I don't know if it dosen't filter anything
    
    // Decided to also use the forEach loop
    let students = [];
    existingUser.forEach(function (u, index) {

    // If the sandwich is turkey, skip it
    if (u === this.state.username;) return;

    // Otherwise log it to the console
    alert(u); // Nothing alerted

});
    // Also decided to use another function I found here on stackoverflow
    let students = filterByValue(existingUser, this.state.username);
    
    if (!students) {
      alert("Email/password combination not correct");
      
    } else {
      alert(students); 
      this.props.navigation.navigate("NewAttendance", { data: students });
    }
    
  render() { 
    return (
            <Container style={styles.contentStyle}>
                <Item inlineLabel style={styles.itemStyle}>
        <MaterialCommunityIcons
                name="Username"
                style={styles.iconStyle}
              />
                    <Label style={styles.labelStyle}>Username</Label>
                    <Input
           autoCapitalize = 'none'
                    style={styles.inputStyle}
                    autoCorrect={false}
                    placeholder="Username" 
                    icon={<Icon name="user" />}
                    onChangeText={data => this.setState({ username: data })}
                    label='Username'
                    />
                </Item>
                <Item inlineLabel style={styles.itemStyle}>
                    <MaterialCommunityIcons
                name="lock"
                style={styles.iconStyle}
              />
                    <Label style={styles.labelStyle}>Password</Label>
                    <Input 
                        style={styles.inputStyle}
                        placeholder="Password"
                        secureTextEntry
                        onChangeText={data => this.setState({ password: data })}
                        label='Password' 
                    />
                </Item>
                    <Button full onPress={this.getStudent} style={styles.buttonStyle}>
                        <Text style={styles.buttonTextStyle}>Login</Text>
                    </Button>
            </Container>
    );
  }
}

正如你所看到的,我首先嘗試了這個,

//let students = existingStudent.filter(es => es.username === this.state.username);// Here nothing will happen. I don't know if it dosen't filter anything

在那之后,我嘗試了這個

    function filterByValue(array, string) {
            return array.filter(o =>
                Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
        }

let students = filterByValue(existingStudent, this.state.username);

然后,我終於嘗試了

foreach 循環

existingStudent.forEach(function (u, index) {
    
        // If the sandwich is turkey, skip it
        if (u === this.state.username;) return;
    
        // Otherwise log it to the console
        alert(u); // Nothing alerted
    
    });

我究竟做錯了什么

它很常見的誤解

AsyncStorage 只能存儲字符串

const students = [{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}]

// store like this
await AsyncStorage.setItem("student", JSON.stringify(students))

// retrieve like tis
const rawStudents = await AsyncStorage.getItem("student")
const students = JSON.parse(rawStudents) // you can check if rawStudents is null before parsing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM