将数据从异步存储推送到 React Native 中的数组对象时项目不显示?

Item not displaying when pushing data from asyncstorage to array object in React Native?

我正在 React Native Expo 中创建一个应用程序并尝试使用异步存储来显示数据。唯一显示的数据是我在 var temp 中声明的静态数组,但是当我将接收到的项目推送到 var temp 中时,它没有显示。我尝试使用 console.log(temp) 检查它是否将数据附加到 temp 变量 。数据正在附加但未显示。谁能告诉我哪里出错了

从异步存储接收数据

readData = async () => {
        try {
            const userData = await AsyncStorage.getItem('ticket')
            if (userData != null) {
                temp.push(JSON.parse(userData))
            }
            console.log(temp)
        }
        catch(e) {
            console.log(e)
        }
    }

    useEffect(() => {
        readData()
    }, [])

显示数据

<View>
                <List.AccordionGroup>
                {
                    temp.map((rowData, index) => (
                        
                            <List.Accordion title={rowData.subject} key={rowData.id} id={rowData.id} style={{marginBottom: 10, backgroundColor: 'white', marginTop: 10,}}>
                                <View style={{padding: 20, backgroundColor: '#FAFAFA'}}>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Project Name:  </Text><List.Item title={rowData.name} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Requested By:  </Text><List.Item title={rowData.request} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Category:  </Text><List.Item title={rowData.category} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Priority:  </Text><List.Item title={rowData.priority}/>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Location:  </Text><List.Item title={rowData.location}/>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Description:  </Text><List.Item title={rowData.desc}/>
                                </View>
                            </List.Accordion>
                        
                    ))
                    
                }
            
                </List.AccordionGroup>
                
            </View>

在 AsyncStorage 中存储数据

handleSubmit = async () => {
        let temp = {
            id: Math.floor(Math.random() * 100),
            name: "",
            request: "",
            subject: "",
            category: "",
            priority: "",
            desc: "",
            location: "",
        };
        temp.name = name
        temp.request = request
        temp.subject = subject
        temp.category = category
        temp.priority = priority
        temp.desc = desc
        temp.location = location
        console.log(temp);
        try {
            // await AsyncStorage.setItem("ticket", JSON.stringify(temp))
            await AsyncStorage.setItem('ticket', JSON.stringify(temp))
            console.log(JSON.stringify(temp));
        }
        catch (e) {
            console.log(e)
        }
    }

静态数组

var temp = [{
    id: 1,
    name: "ECM DMS",
    request: "Sohail",
    subject: "Laptop Repair",
    category: "IT",
    priority: "Medium",
    desc: "Urgent Repair",
    location: "Pune",
}];

userData 存储在 asyncstorage

Object {
    "category": "Sharepoint",
    "desc": "Access",
    "id": 20,
    "location": "Mumbai",
    "name": "SharePoint access",
    "priority": "Low",
    "request": "Gurmar",
    "subject": "Access",
  },

对于 UI 级别的更改,您必须使用状态来告诉 react-native 在状态值更改时更新 UI。

因此您必须将 temp 设置为数据的状态。

例如

const [data, setData] = useState([]);

并且当您要更新数据以显示在您的设计中时,您必须通过调用 setData 方法更新状态,并将旧状态更改为新状态以使用现有数据值更新新数据。

例如

setState(prevState => [...prevState, <<NEW_DATA_OBJECT>>]);

它将更新状态,这是在 UI 中显示更新数据的方式, 当您处理新数据的提交时,您只需在临时和更新状态的位置使用数据常量。

这里是如何使用 AsyncStorage 存储和检索数据的完整示例。

工作应用程序:Expo App

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { List } from 'react-native-paper';
const temp = [
  {
    id: 1,
    name: 'ECM DMS',
    request: 'Sohail',
    subject: 'Laptop Repair',
    category: 'IT',
    priority: 'Medium',
    desc: 'Urgent Repair',
    location: 'Pune',
  },
];
export default function App() {
  const [data, setData] = useState([]);

  const handleSubmit = async () => {
    let temp = {
      id: Math.floor(Math.random() * 10000),
      name: 'ECM DMS',
      request: 'Sohail',
      subject: 'Laptop Repair' + Math.floor(Math.random() * 200),
      category: 'IT',
      priority: 'Medium',
      desc: 'Urgent Repair',
      location: 'Pune',
    };

    // console.log(temp);
    try {
      await AsyncStorage.setItem('ticket', JSON.stringify([...data, temp]));
      // console.log(JSON.stringify(temp));
      setData([...data, temp]);
      AsyncStorage?.getItem('ticket').then((userData) =>
        console.log('read data submit:' + JSON.stringify(JSON.parse(userData)))
      );
    } catch (e) {
      console.log('handle:', e);
    }
  };

  const readData = async () => {
    try {
      const userData = await AsyncStorage?.getItem('ticket');
      if (userData != null) {
        setData(JSON.parse(userData));
        console.log('read data:' + JSON.stringify(JSON.parse(userData)));
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    readData();
  }, []);
  return (
    <View style={styles.container}>
      <View>
        {data.length > 0 && (
          <List.AccordionGroup>
            {data?.map((rowData, index) => (
              <List.Accordion
                title={rowData.subject}
                key={rowData.id}
                id={rowData.id}
                style={{
                  marginBottom: 10,
                  backgroundColor: 'white',
                  marginTop: 10,
                }}>
                <View style={{ padding: 20, backgroundColor: '#FAFAFA' }}>
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Project Name:{' '}
                  </Text>
                  <List.Item title={rowData.name} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Requested By:{' '}
                  </Text>
                  <List.Item title={rowData.request} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Category:{' '}
                  </Text>
                  <List.Item title={rowData.category} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Priority:{' '}
                  </Text>
                  <List.Item title={rowData.priority} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Location:{' '}
                  </Text>
                  <List.Item title={rowData.location} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Description:{' '}
                  </Text>
                  <List.Item title={rowData.desc} />
                </View>
              </List.Accordion>
            ))}
          </List.AccordionGroup>
        )}
      </View>

      <Button title={'ADD MORE DATA'} onPress={handleSubmit} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});