开发者问题收集

useState 定义的状态变量在 React Native 中不起作用

2022-02-14
141

有人能找出这段代码中有什么问题吗?从 flatlist 中什么也没得到。状态变量 items 也显示为 null。

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. Heyy

LOG 2. m Gnutella fits n me gobo dl

LOG 3. Fnch h gcc

LOG 4. Geysgdsfsgd

LOG 5. Dyrydydyd

LOG 6. Vjvjvj

LOG 7. Xbxbx

LOG 8. Gdgx

LOG 9. Xvxdh

ERROR TypeError:未定义不是对象(正在评估'val.item')

2个回答

你需要稍微改变一下你的 FlatList& renderlist,不要忘记大写。 试试这个:

const RenderList = ({val}) => {
    return(<Text>{val.item}</Text>)
    
  }
<FlatList 
        data={items} 
        renderItem={({ item }) => (
        <RenderList val={item}
        />
      )}/>
Hen Moshe
2022-02-14

尝试以下方法:

useEffect(() => {
    if(!items.length){
     init();
    }
  }, [items]);
Nicholas Mberev
2022-02-14