1

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

从异步存储接收数据

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",
}];

存储在 asyncstorage 中的 userData

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

2 回答 2

1

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

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

例如。

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

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

例如。

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

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

于 2021-02-05T05:54:37.103 回答
1

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

工作应用程序:世博会应用程序

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,
  },
});

于 2021-02-05T06:51:29.637 回答