无法使用地图功能react-native

亚历山德鲁·西玛(Alexandru Sima)

我是本机新手,我正在使用异步存储来存储对象,然后通过将它们存储在收藏夹数组中进行解析。我试图映射数组中的每个元素并显示它。

我收到此错误:this.state.favorites.map不是函数。我认为这是状态错误,但是由于我是这些概念的新手,所以我不知道如何解决它。请帮忙。

import React, {Component} from 'react';
import {StyleSheet, Text, View, Image,  FlatList, Button, AsyncStorage, 
TouchableOpacity} from 'react-native';
import ajax from './ajax.js';
import PropTypes from 'prop-types';
import InspirationList from './InspirationList';
import FavoriteItem from './FavoriteItem';
import ProductItem from './ProductItem';


class Favorites extends Component{
    state = {
        favorites:[],
      };

componentDidMount(){
    this.showProduct();
  }

    async showProduct() {
        let k=0;
        AsyncStorage.getAllKeys()
            .then(keys => AsyncStorage.multiGet(keys)
            .then((result) => {
                result.map(req => req.forEach((element) => {
                    k++;
                    if(element!=null && k%2==0){
                    this.setState({favorites: JSON.parse(element) });
                    console.log(this.state.favorites.nume);
                     }
                  }));       
            }));
        };

  render(){
    return(
    <View style='styles.fav'>
        {this.state.favorites.map((fav)=>
            <Text>{fav.nume}</Text>
        )}
    </View>
    );
  }
}

const styles = StyleSheet.create({  
 fav:{
     backgroundColor:'#999',
     flex:1,
     width:'100%',
     paddingTop:150,
 }
});

export default Favorites;
约瑟

在您的showProduct职能上,您将覆盖原来的状态。分配时,JSON.parse(element)您正在更改状态而不是拥有数组,而是将其转换为对象,这就是为什么会出现该错误的原因。map仅在类似数组的数组中存在。

因此,也许您可​​以执行以下操作:

async showProduct() {
        let k=0;
        AsyncStorage.getAllKeys()
            .then(keys => AsyncStorage.multiGet(keys)
            .then((result) => {
                result.map(req => {
                  let result = [];
                  req.forEach((element) => {
                    k++;                        
                    if(element!=null && k%2==0){
                      result.push(JSON.parse(element))
                    }
                    });
                  this.setState({favorites: result });}
              );       
            }));
        };

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章