首页 > 解决方案 > 为什么我调用一次时会打印无限值?

问题描述

它不断调用 addName 函数无限 -

//hook for displaying the names in the database
const [names, setNames] = useState([]);

console.log(names);
//inserts a name into the database, calls update if successful
const addName = () => {
  let newName = `${"empty"}-${"empty"}`;

  db.transaction((tx) => {
    tx.executeSql("INSERT INTO Names(name) VALUES (?)", [newName], update());
  });
  //add the results of the database into the names hook
  const update = () => {
    console.log(db);
    db.transaction((tx) => {
      tx.executeSql(
        "SELECT name from Names",
        [],
        (tx, { rows }) => {
          setNames(() => {
            let retRA = [];
            rows._array.forEach((elem) => {
              retRA.unshift(elem.name);
            });
            return retRA;
          });
        },
        (tx, error) => {
          console.log("ERRORE-->SQLITE--->", error);
        }
      );
    });
  };
};
addName();

标签: react-nativesqliteexpohook

解决方案


看起来您正在调用addName组件的主体。因为addName更新状态,这将导致无限循环。

addName仅在需要时(用户按下按钮后)或组件安装时尝试调用。


推荐阅读