0

有人可以找出这段代码有什么问题吗?从平面列表中一无所获。状态变量 items 也显示为空。

import React, { useEffect, useState } from 'react';
import { FlatList, SafeAreaView, TextInput, Text, Button, Alert } from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';

const db = openDatabase({name: 'sqlitedb3 '});

const App = () => {

  const [text, setText] = useState('');
  const [items, setItems] = useState([]);

  async function init() {
    await handleInit();
    await handleFetch();
  }

  useEffect(() => {
    init();
  }, [])

  const handleInit = async() => {
    await db.transaction((txn) => {
      txn.executeSql('CREATE TABLE IF NOT EXISTS Items ('+
        'id INTEGER PRIMARY KEY AUTOINCREMENT,'+
        'item VARCHAR(30))', [], (tx, res) => {
        console.log('table created');
      })
    })
  }

  const handleFetch = async() => {
    await db.transaction((txn) => {
      txn.executeSql('SELECT * FROM Items', [], (tx, res) => {
        let n = res.rows.length;
        console.log('fetched '+n+' items');
        let result = [];
        for(let i = 0; i < n; i++) {
          result.push({id: res.rows.item(i).id, item: res.rows.item(i).item });
          console.log(res.rows.item(i).id+". "+res.rows.item(i).item)
        }
        setItems(result);
        console.log('state.items: '+items.length)
      })
    })
  }

  const handleSubmit = async() => {
    console.log('submit pressed');
    if(text === null || text === '') {
      Alert.alert('text input is blank');
      return;
    }
    
    try {
      await db.transaction((txn) => {
        txn.executeSql('INSERT INTO Items (item) VALUES (?)', [text],async (tx, res) => {
          console.log('saved successfully');
          setText('');
          await handleFetch();
        })
      })
    }
    catch(err) {
      console.log("can't submit")
    }
  }

  const renderlist = ({val}) => {
    return(<Text>{val.item}</Text>)
    
  }

  return(
    <SafeAreaView>
      <TextInput 
        value={text} 
        onChangeText={(val)=>setText(val)} />
      <Button
        onPress={() => { handleSubmit() }}
        title='Submit'/>
      <Text>Hello</Text>
      <FlatList 
        data={items} 
        renderItem={renderlist}
      />
    </SafeAreaView>
  )
}

export default App;

控制台输出:

LOG 表已创建

LOG 表已创建

LOG 提交已按下

LOG保存成功

LOG 获取了 9 个项目

LOG 1.嘿嘿

LOG 2. m Gnutella 适合我 gobo dl

LOG 3. Fnch h gcc

LOG 4. Geysgdsfsgd

LOG 5. Dyrydydyd

日志 6. Vjvjvj

日志 7. Xbxbx

日志 8.Gdgx

日志 9.Xvxdh

错误类型错误:未定义不是对象(评估“val.item”)

4

2 回答 2

1

你需要稍微改变你的 FlatList& 渲染列表,不要忘记大写。试试这个:

 const RenderList = ({val}) => {
    return(<Text>{val.item}</Text>)
    
  }
<FlatList 
        data={items} 
        renderItem={({ item }) => (
        <RenderList val={item}
        />
      )}/>
于 2022-02-14T18:20:34.727 回答
0

尝试这样的事情:

useEffect(() => {
    if(!items.length){
     init();
    }
  }, [items]);
于 2022-02-14T18:21:42.160 回答