【问题标题】:How to use AsyncStorage to store array in React NativeReact Native 中如何使用 AsyncStorage 存储数组
【发布时间】:2020-03-09 23:21:58
【问题描述】:

我正在尝试使用 AsyncStorage 来存储使用 React Native 的简单配置文件。

这是我到目前为止添加配置文件的内容,我尝试了 console.log(contact),但什么也没显示。

 function AddContact(props) {

  const [FName,setFName] = useState('');
  const [LName,setLName] = useState('');
  const [PNumber,setPNumber] = useState('');

  var contact = {
    firstname : FName,
    lastname : LName,
    phonenumber : PNumber
  };

  const storeContact = async() => {
    try {
      await AsyncStorage.setItem(
        '@MySuperStore:key', JSON.stringify(contact));

    } catch (error) {
    // Error saving data
  }}

For Loading Profile


  const loadContact = async () => {
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:key', JSON.stringify(contact));
      if (value !== null) {
        // We have data!!
        console.log(value);
      }
    } catch (error) {
      // Error retrieving data
    }
  };

请帮忙。

【问题讨论】:

    标签: react-native async-await asyncstorage


    【解决方案1】:

    AsyncStorage.getItem() 只接受一个关键参数。所以你必须只传递参数“key”,它会将你的数据作为字符串返回:

    const value = await AsyncStorage.getItem('@MySuperStore:key');
    

    或者如果你想使用这个value作为数组来显示你必须将它转换成json的东西。

    const loadContact = async () => {
      try {
        const value = await AsyncStorage.getItem('@MySuperStore:key');
        if (value !== null) {
          // We have data!!
          console.log(value);
          this.setState({
            data: JSON.parse(value);
          });
        }
      } catch (error) {
        // Error retrieving data
      }
    };
    

    【讨论】:

      【解决方案2】:

      为了从异步存储中加载数据,您的 loadContact 方法应该是:

      For Loading Profile
      
      
        const loadContact = async () => {
          try {
            const value = await AsyncStorage.getItem('@MySuperStore:key');
            const json = JSON.parse(value); // this is how you get back the array stored
            if (json !== null) {
              // We have data!!
              console.log(value);
            }
          } catch (error) {
            // Error retrieving data
          }
        };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        相关资源
        最近更新 更多