reactjs - React hooks如何在初始useEffect之后跳过特定的useEffect
问题描述
我有以下代码,如何防止AsyncStorage.setItem
在初始渲染时被调用 2 次?它被调用[]
并加载任何内容,AsyncStorage
因为logs
已更新。完美的解决方案根本不应该调用setItem
,因为logs
刚刚从AsyncStorage
.
const AsyncStorage = require("@react-native-community/async-storage")
const useStore = () => {
const [logs, setLogs] = useState([])
useEffect(() => {
AsyncStorage.getItem("logs").then((newLogs) => setLogs(newLogs));
}, [])
useEffect(() => {
//Don't want to setItem on initial load or when `logs` was just loaded.
AsyncStorage.setItem("logs", JSON.stringify(logs));
}, [logs])
const addLog = (newText) => {
setLogs(logs => [
{text: newText, createdAt: new Date().getTime()},
...logs,
]);
}
return {
logs,
addLog,
//...many other functions that update logs
}
}
解决方案
我认为包装你的 set state 方法是一种更简洁的方法来控制日志何时应该发生。像这样的东西:
const AsyncStorage = require("@react-native-community/async-storage")
const useStore = () => {
const [logs, setLogsState] = useState([])
const persistLogsRef = useRef(false)
const setLogs = (updatedLogs) => {
persistLogsRef.current = true
setLogsState(updatedLogs)
}
useEffect(() => {
AsyncStorage.getItem("logs").then((newLogs) => setLogsState(newLogs));
}, [])
useEffect(() => {
//Don't want to setItem on initial load or when `logs` was just loaded.
if (persistLogsRef.current) {
AsyncStorage.setItem("logs", JSON.stringify(logs));
}
}, [logs])
const addLog = (newText) => {
setLogs(logs => [
{text: newText, createdAt: new Date().getTime()},
...logs,
]);
}
return {
logs,
addLog,
//...many other functions that update logs
}
}
推荐阅读
- python - 劫持轮廓模型
- python - 为什么 gensim FastText 模型的大小比 Facebook 的原生 Fasttext 模型小?
- angular - NgRx 效果单元测试混淆了 Jasmine 间谍调用计数
- excel - Excel:计算每个网格单元的面积
- containers - 解析配置失败:/loki/conf/local-config.yaml:yaml:unmarshal:在 storage.Config 类型中找不到字段压缩器
- sockets - 如何获取 ssl 证书并使用套接字安全地连接到服务器
- php - PHP 7 从 mssql 迁移到 sqlsrv 问题
- pine-script - Pinescript - strategy.exit() 的数量如何自行变化?
- android - 为没有 Netowrk 的配对手机纠正 Android 汽车拨号器中的断开原因
- javascript - 使用使用 GraalVM 和 Java 接受字节数组的 Javascript 函数