【发布时间】:2020-08-18 00:16:20
【问题描述】:
我的组件大致是这样的:
import useCustomHook from "./hooks";
const Test = () => {
const [data, setData] = useCustomHook("example-key", {ready: false});
return (
data.ready ?
<>
{console.log("data is ready");}
<ComponentA />
</> :
<>
{console.log("data is not ready");}
<ComponentB />
</>
)
}
useCustomHook 是从AsyncStorage 提取的用于我的本机应用程序的辅助钩子,因此它有一点延迟。 当我运行它时,我看到控制台日志“数据未准备好”,然后是“数据准备好”,但我只看到 ComponentB 渲染,而从来没有看到 ComponentA。
如果有帮助,自定义挂钩如下所示。它基本上只是将 JSON 序列化为一个字符串进行存储。
export default (key, initialValue) => {
const [storedValue, setStoredValue] = React.useState(initialValue);
React.useEffect(() => {
const populateStoredValue = async () => {
const storedData = await AsyncStorage.getItem(key);
if (storedData !== null) {
setStoredValue(JSON.parse(storedData))
}
}
populateStoredValue()
}, [initialValue, key]);
const setValue = async (value) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
await AsyncStorage.setItem(key, JSON.stringify(valueToStore));
setStoredValue(valueToStore);
}
return [storedValue, setValue];
}
有人对这里可能发生的事情有想法吗?
谢谢!
小 PS:我还看到了警告 Sending "onAnimatedValueUpdate" with no listeners registered.,这似乎是 react-navigation 无关的事情。但只是想把它放在这里。
【问题讨论】:
-
你能用帮助代码编辑线程吗
-
当然,会编辑!
标签: reactjs react-native react-hooks conditional-operator conditional-rendering