为什么我调用一次时打印无限值?
Why prints infinite value when I call it once?
一直无限调用addName函数-
- expo hooks SQLite .
//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();
您似乎在组件主体中调用 addName
。因为 addName
更新状态,这将导致无限循环。
尝试仅在需要时(在用户按下按钮后)或组件安装时调用 addName
。
一直无限调用addName函数-
- expo hooks SQLite .
//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();
您似乎在组件主体中调用 addName
。因为 addName
更新状态,这将导致无限循环。
尝试仅在需要时(在用户按下按钮后)或组件安装时调用 addName
。