更新useState和AsyncStorage并根据给定结果重新渲染屏幕

时间:2020-07-22 19:57:59

标签: reactjs react-native asyncstorage

我是React Native的新手,我目前正在尝试从网站获取凭据数据并将其保存到设备内存中。但是,与此相关的问题很少!

我的流程:

  1. 启动应用程序时,应用程序将检查asyncStorage是否有凭据。

  2. 如果是这样,我们将直接进入该应用程序。否则,我们进入RootStackScreen(又名登录屏幕)***(问题1)

  3. (登录)用户将其登录名输入文本输入,该文本输入将保存在useState中。

  4. 使用函数'loginHandle',使用useState中的信息调用获取请求,然后我们将setCredential与返回的数据一起使用。**(问题2)

  5. 应用程序应重新呈现,并看到有凭据并加载到主屏幕中。 ***(问题3)

但是,我遇到了2个问题。

  1. ***即使当我在return(...)中检查appLoad.credentials时,即使asyncStorage确实包含凭据,它也会返回null。但是,它在我的useEffect()中返回正确的值。我认为通过使用useEffect()可以在呈现屏幕之前在ComponentsDidMount期间调用函数。那么appLoad.credentials是否不应包含字符串?

  2. 在我的console.log(凭据)上,它总是落后一步。即我按一次登录按钮。控制台日志将返回null。但是,我认为由于console.log()在fetch命令之后,因此应该在console.log调用之前设置凭据!

  3. 如何重新渲染应用程序。我在网上看到过有关强制换发的信息,但听说这很糟糕!

App.js


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

export default function App() {

  const STORAGE_KEY = '@deviceCredentials';
  const [data, setData] = useState('');

  const appLoad = {
    isLoading: true,
    credentials: null
  };


  //Runs during ComponentsDidMount
  useEffect(() => {
    setTimeout(async () => {

      //In 1000ms try to get credentials
      try {
        appLoad.credentials = await AsyncStorage.getItem(STORAGE_KEY);
        console.log(appLoad.credentials);
      } catch (e) {
        console.log(e);
      }
    }, 1000);
  }, []);


  //Render
  return (
 
      <NavigationContainer>
        {/* If credentials is not null then we can go straight into Main screen, 
            otherwise we go to Login Screen */}
        {appLoad.credentials !== null ? (
          <Drawer.Navigator drawerContent={props => <DrawerContent {...props} />}>
            <Drawer.Screen name="MusteringDrawer" component={MainTabScreen} />
          </Drawer.Navigator>
        )
          :
          <RootStackScreen />
        }
      </NavigationContainer>

  );
};

SignIn.js

...
...
const [data, setData] = useState({
                               username: '',
                               password: '',
                               ...
})
const [credential, setCredential] = useState({ data: null });

const STORAGE_KEY = '@deviceCredentials';

...
...
//Handles user data
const handleValidUser = (val) => {
            setData({
                ...data,
                username: val,
            });
}


const loginHandle = () => {
        fetch(url + data.password + data.username)
            .then(x => x.text())
            .then(y => {
                setCredential({ data: y });
            });
            console.log(credential);
            AsyncStorage.setItem(STORAGE_KEY, credential);
    }



return( 
     <Text>Username</Text>
     <TextInput
        placeholder="Your Username"
        onChangeText={(val) => handleValidUser(val)}
        onEndEditing={(e) => handleValidUser(e.nativeEvent.text)}
      />
     <Text>Password</Text>
     <TextInput
         placeholder="Your Password"
         onChangeText={(val) => handlePasswordChange(val)}
      />


      <View style={styles.button}>
            <TouchableOpacity  onPress={() => { loginHandle(); }}>
                   <Text>Sign In</Text>
            </TouchableOpacity>
      </View>

1 个答案:

答案 0 :(得分:1)

您是否知道以下事实:

const appLoad = {
    isLoading: true,
    credentials: null
};

每个渲染都重新定义吗?更重要的是,如果在效果挂钩中设置了该值,则react无法得知它已被更改,因此不会重新渲染。如果确实要重新渲染(出于某些完全不同的原因,此不会重新渲染)...那么,新变量:D。

您想要的是在所有渲染器中记住这样的数据。如您所知,您可以使用useState钩子来完成此操作。

免责声明:阅读我在代码中的注释非常重要,它们对于使代码成为“最佳实践”至关重要。该代码也没有经过测试,但是您应该可以使用一些熟练的开发人员技能使它起作用:)

export default function App() {
    // Remove this, seems to be a leftover from testing 
    // const [data, setData] = useState('');
    
    const [isLoading, setIsLoading] = useState(true);
    const [credentials, setCredentials] = useState(null);

    // Check for credentials in the first render
    useEffect(() => {
        // 1. I'm not sure why you add a delay, It will probably only make your app appear sluggish
        // 2. Use effect callbacks should not be made async, see this post 
        // https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret
        async function fetchCredentials() {
            setCredentials(await AsyncStorage.getItem(STORAGE_KEY));
            setIsLoading(false); 
        }

        fetchCredentials();
    }, []);

    // Whatever your render code may be
    return null;
}

很有可能我还没有解决您的问题(我可能会想念您,而且大多数时候我通常都有些愚蠢)。在这种情况下,请随时通过评论回复我。

欢呼和快乐的编码!