代碼
PrizeHistory.js
...
const PrizeHistory = () => {
const [history, setHistory] = useState([]);
useEffect(() => {
async function getHistory () {
try {
let result = await sqliteInterface.getAllPrizes(db, prizeTable);
result == null ? console.log("res is null") : setHistory(result);
console.log("result" result);
console.log("history" history);
} catch (err) {
console.log(err);
}
}
getHistory();
}, [history])
return (
<View style={styles.body}>
<Text style={styles.text}>Prize History</Text>
</View>
);
}
獲得所有獎品
getAllPrizes(db, tableName) {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql(
`SELECT * FROM ${tableName};`,
[],
(tx, res) => {
let len = res.rows.length;
let results = [];
if(len > 0) {
for(i = 0; i < res.rows.length; i ) {
results.push(res.rows.item(i));
}
}
console.log("resolving promise now");
resolve(JSON.stringify(results));
},
(error) => {
reject(Error(`SQLite getAllPrizes: failed to get '*' from ${tableName}: ` error));
}
);
});
});
}
目標
掛載頁面時,將歷史狀態設定為資料庫中的資料。我最初嘗試過這個:
useEffect(() => {
async function getHistory () {
try {
let result = await sqliteInterface.getAllPrizes(db, prizeTable);
result == null ? console.log("res is null") : setHistory(result);
console.log("result" result);
console.log("history" history);
} catch (err) {
console.log(err);
}
}
getHistory();
}, [])
但它從未正確設定我的歷史變數。我剛得到一個空陣列(這是我最初將歷史狀態設定為的)。我希望 history 變數等于 history 中的結果變數console.log(),但事實并非如此。
所以我改成useEffect()這樣:
useEffect(() => {
async function getHistory () {
try {
let result = await sqliteInterface.getAllPrizes(db, prizeTable);
result == null ? console.log("res is null") : setHistory(result);
console.log("result" result);
console.log("history" history);
} catch (err) {
console.log(err);
}
}
getHistory();
}, [history])
這段代碼正確地更改了歷史變數,但我預計它會進入無限回圈......但它沒有?這是我的邏輯
useEffect()有[history]作為依賴- onMount,
history設定為默認值[] useEffect()seeshistory已設定并開始運行useEffect()重置historyuseEffect()應該重新開始,因為它重置了history變數本身- 無限重復3-5...
但它不會無限重復......
我的問題
- 設定為依賴項
useEffect()時為什么不無限運行[history] useEffect()當它具有[]依賴性時,為什么沒有在 mount 上正確設定我的歷史變數。
uj5u.com熱心網友回復:
您的 1 個問題的答案是:history第一次設定后不會改變,因為您的getAllPrizes回傳值始終相同,因此useEffect僅觸發一次(安裝時)。
對于第二個問題,問題是您試圖history在呼叫 之后立即記錄值setHistory,這是異步的。如果您想在history每次更新時都進行記錄,您必須執行以下操作:
useEffect(() => {
console.log(history)
}, [history])
uj5u.com熱心網友回復:
您確定您沒有嘗試在此行上設定字串型別嗎:
result == null ? console.log("res is null") : setHistory(result);
據我所知,初始型別是一個陣列,resolve 函式回傳一個字串化的物件。您是否在控制臺中收到任何警告?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399036.html
標籤:javascript 反应 反应钩子 使用效果
