【问题标题】:I cant iterate over an array of objects我无法遍历对象数组
【发布时间】:2020-11-08 14:05:53
【问题描述】:

我正在开发一个 react 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
    
    });

我做错了什么

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    这是很常见的误解

    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
    
    

    【讨论】:

    • 这是我采取的第一步,但是当我提醒它时,它是这样显示的[object Object], object Object], object Object], object Object]
    • 你没看到有一个 JSON.stringify
    猜你喜欢
    • 2018-03-08
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多