简体   繁体   English

如何在本机反应中将 state 值设置为数组?

[英]How to set a state value to an array in react native?

I have a functional component, ListKeys .我有一个功能组件ListKeys When it loads I want to set an empty array of keys equal to a list of all keys extracted from storage.当它加载时,我想设置一个空的键数组,等于从存储中提取的所有键的列表。 Here is what I've got at the moment:这是我目前所拥有的:

 const ListKeys = props => {
    const [keys, setKeys] = useState([]);
    const [areKeysLoaded, setAreKeysLoaded] = useState(false);

    useEffect(() => {
        if(!areKeysLoaded){
            loadSavedKeys();
            setAreKeysLoaded(true);
            console.log(keys)
        }
    });

    async function loadSavedKeys(){
        try {
            var allKeys = await AsyncStorage.getAllKeys();
            console.log(allKeys);
            setKeys(allKeys);
        }
        catch {
            console.log("Error: Cannot access saved data.");
        }
    }

    return (
        <View></View>
    );

};

export default ListKeys;

This code correctly gets the list of keys and outputs it to the console.此代码正确获取键列表并将其输出到控制台。 This is done on line 16: console.log(allKeys);这是在第 16 行完成的: console.log(allKeys);

However, when I then setKeys(allKeys);但是,当我然后setKeys(allKeys); , this doesn't work. ,这不起作用。 I know this because line 9: console.log(keys) outputs an empty array.我知道这是因为第 9 行: console.log(keys)输出一个空数组。

I'm guessing I can't just set a state value array to another array but I'm not experienced enough with JS or React Native to know why.我猜我不能只将 state 值数组设置为另一个数组,但我对 JS 或 React Native 的经验不够了解原因。

Can someone tell me how to properly set the keys array to the allKeys array?有人能告诉我如何正确地将keys数组设置为allKeys数组吗?

You need to wait for the loadSavedKeys to resolve first before trying to set since it is async :您需要先等待loadSavedKeys解决,然后再尝试设置,因为它是async

const ListKeys = props => {
    const [keys, setKeys] = useState([]);
    const [areKeysLoaded, setAreKeysLoaded] = useState(false);

    useEffect(() => {
      if (areKeysLoaded) return
      AsyncStorage
        .getAllKeys()
        .then((keys) => {
          setAreKeysLoaded(true)
          setKeys(keys)
        })
        .catch(e => console.error(e));
    }, []);

    return (
        <View></View>
    );

};

export default ListKeys;

Note I simplified the code a bit since it seemed a little more verbose then necessary.注意我稍微简化了代码,因为它看起来有点冗长,然后是必要的。 They key take away is you need to wait for getAllKeys to resolve before you'll get the keys since it is asynchronous.他们的关键是您需要等待getAllKeys解决,然后才能获得密钥,因为它是异步的。

Also, you prob don't need areKeysLoaded if you just want this to run once, but I guess you could use it instead for a loading indicator?另外,如果您只想让它运行一次,您可能不需要areKeysLoaded ,但我想您可以使用它来代替加载指示器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM