【问题标题】:set state not working react hooks(string) asyncStorage [duplicate]设置状态不起作用反应钩子(字符串)异步存储[重复]
【发布时间】:2020-05-30 19:08:29
【问题描述】:

嘿,我正在使用 react-natives-community 异步存储,我这辈子都无法保存状态,我不太清楚为什么。 await 变量中的第一个 console.log 返回正确的信息,但是当我设置状态时,第二个 console.log 返回 null 并且我不确定发生了什么

const [userEmail, setUserEmail] = useState<string | null>(null);

const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')

我做了这个自定义钩子,但仍然没有运气

const useGetAsyncStorage = (AsyncStorageItem: string): string => {
  try {
    const [data, setData] = useState<string | null>(null);
    useEffect(() => {
      const fetchAsyncStorage = async () => {
        const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
        console.log(AsyncStorageData)
        setData(AsyncStorageData);
      };
      fetchAsyncStorage();
    }, [AsyncStorageItem]);

    return data as string
  } catch (error) {
    return error
  }
};

【问题讨论】:

  • 问题是状态更新是异步的。您最终会看到与 first 相同的结果。如果你想看到变化,你应该在 useEffect() 钩子中做 console.log。

标签: javascript reactjs typescript react-native react-hooks


【解决方案1】:

问题是状态更新是异步的。您最终会看到该电子邮件的 null 是它最初的样子。如果你想看到变化,你应该在 useEffect() 钩子中做 console.log

【讨论】:

  • 那么我将如何更新状态。因为我看不到相同的结果,第一个是(johnDoe@gmail.com),第二个是(null)
  • 其实不会和first一样,应该是previous state,为null。我更新了我的答案
  • 所以我做了这个自定义钩子,但它仍然无法正常工作const useGetAsyncStorage = (AsyncStorageItem: string): string =&gt; { try { const [data, setData] = useState&lt;string | null&gt;(null); useEffect(() =&gt; { const fetchAsyncStorage = async () =&gt; { const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem); console.log(AsyncStorageData) setData(AsyncStorageData); }; fetchAsyncStorage(); }, [AsyncStorageItem]); return data as string } catch (error) { return error } };
猜你喜欢
  • 1970-01-01
  • 2020-06-27
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 2019-12-21
  • 2020-09-27
相关资源
最近更新 更多