AsyncStorage.setItem返回null(等待获取完成)

时间:2019-12-08 19:51:56

标签: json react-native

通过获取,我正在从服务器获取JWT。之所以会收到此JWT,是因为当我执行console.log(resData.token)时,令牌会显示在控制台中。但是我无法将令牌保存在异步存储中。响应是这样的:

{“ _ 40”:0,“ _55”:null,“ _65”:0,“ _72”:null}

我认为当asynstorage.setItem运行时,获取尚未完成,但是我如何等待它首先完成?

import React, { useState } from 'react';
import { Text, TextInput, Button, SafeAreaView } from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';

const SignInScreen = props => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const SignInHandler = async () => {    
    const req = await fetch('http://localhost:8080/auth/signin', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({username: username, password: password})
    });
    const res = await req;
    if (res.ok) {
      const resData = await res.json();
      console.log(resData.token); // this works!
      await AsyncStorage.setItem('token', JSON.stringify(resData.token));
      console.log(AsyncStorage.getItem('token')); // this does not work
    } else {
      console.log('no user found');
    };
  };
  return (
    <SafeAreaView>
      <Text>Username</Text>
      <TextInput value={username} onChangeText={username => setUsername(username)} />
      <Text>Password</Text>
      <TextInput value={password} onChangeText={password => setPassword(password)} />
      <Button title="Sign In" onPress={SignInHandler} />    
    </SafeAreaView>
  );
};

SignInScreen.navigationOptions = navigation => ({
  headerShown: false
});

export default SignInScreen;

2 个答案:

答案 0 :(得分:2)

AsyncStorage中的方法是异步的。您可以这样使用它:

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
    List<Product_List> product_lists;
    Context ct;

    public ProductAdapter(List<Product_List> product_lists, Context ct) {
        this.product_lists = product_lists;
        this.ct = ct;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view=
                LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.product_list,viewGroup,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, int i) {
        final Product_List productList=product_lists.get(i);
        String pimg=productList.getImage();

        Picasso.get().load(pimg).into(viewHolder.img);


        viewHolder.tv.setText(productList.getName());
        if (MainActivity.favoriteDatabase.favoriteDao().isFavorite(productList.getId())==1)
            viewHolder.fav_btn.setImageResource(R.drawable.ic_launcher_background);
        else
            viewHolder.fav_btn.setImageResource(R.drawable.ic_launcher_foreground);


        viewHolder.fav_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FavoriteList favoriteList=new FavoriteList();

                int id=productList.getId();
                String image=productList.getImage();
                String name=productList.getName();

                favoriteList.setId(id);
                favoriteList.setImage(image);
                favoriteList.setName(name);

                if (MainActivity.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
                    viewHolder.fav_btn.setImageResource(R.drawable.ic_launcher_background);
                    MainActivity.favoriteDatabase.favoriteDao().addData(favoriteList);

                }else {
                    viewHolder.fav_btn.setImageResource(R.drawable.ic_launcher_foreground);
                    MainActivity.favoriteDatabase.favoriteDao().delete(favoriteList);

                }


            }
        });
    }


    @Override
    public int getItemCount() {
        return product_lists.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        ImageView img,fav_btn;
        TextView tv;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            img=(ImageView)itemView.findViewById(R.id.img_pr);
            tv=(TextView)itemView.findViewById(R.id.tv_name);
            fav_btn=(ImageView)itemView.findViewById(R.id.fav_btn);

        }
    }
}

您可以找到更多信息here in the doc

答案 1 :(得分:0)

{"_40": 0, "_55": null, "_65": 0, "_72": null}

这表示未兑现承诺。 异步存储会返回必须解决的Promise中的值。

尝试使用异步-等待功能来解决此问题。

await AsyncStorage.setItem('token', JSON.stringify(resData.token)); console.log(await AsyncStorage.getItem('token'));

这将解决问题