如何使用 react native 中的其他组件更新 app.js 的状态?

时间:2021-05-31 13:26:14

标签: javascript reactjs react-native

我正在使用 native-CLI 来构建 react-native 应用程序。一切正常,但是当我通过 API 登录用户时,我收到令牌和其他值。我将它们设置在 AsyncStorage 中,它应该跳转到买家仪表板屏幕,但它不能,但是当我刷新应用程序时,它会转到买家仪表板。基本上,按下登录按钮后它不会刷新 app.js,它也应该刷新 app.js。

登录按钮代码

const login = async () => {
        if (name != '' && password != '') {
            const login_Credentials = new FormData();
            login_Credentials.append('username', name);
            login_Credentials.append('password', password);
            setPress(true)
            await axios({
                method: 'POST',
                url: api + 'login/',
                data: login_Credentials,
                headers: { 'Content-Type': 'multipart/form-data' }
            }).then(async function (response) {
                if (response.data.Success == true) {
                    const token = response.data.token.toString();
                    const super_user_status = response.data.super_user_status.toString();
                    const isLoggedIn = "1"
                    console.log('Logged In and set Storgae')
                    await AsyncStorage.multiSet([['isLoggedIn',isLoggedIn],['token', token], ['super_user_status', super_user_status]])
                    setName('')
                    setPassword('')
                    setPress(false)
                } else if (response.data.Success == false) {
                    setPress(false)
                    setErrorMsg(response.data.Error)
                    setName('')
                    setPassword('')
                    
                }
            }).catch(function (response) {
                console.log(response, "error");
            })
        } else {
            setErrorMsg('Please Enter Username/Password.')
        }
    }

app.js

const App = () => {
  const [user, setUser] = useState(false)
  const [role, setRole] = useState('seller')

  useEffect(()=>{ 
    getKeysData(dataKeys)
  },[]) 

  const dataKeys = ['token', 'super_user_status', 'isLoggedIn'];    
  const getKeysData = async (keys) => {
    const stores = await AsyncStorage.multiGet(keys);
    const aData = stores.map(([key, value]) => ({ [key]: value }))
    const token = aData[0]['token']
    const super_user_status = aData[1]['super_user_status']
    const isLoggedIn = aData[2]['isLoggedIn']
    console.log('token',token)
    console.log('SuperUser', super_user_status)
    console.log('Log',isLoggedIn)
    if(isLoggedIn == '1'){
      setUser(true)
    }else{
      setUser(false)
    }
    }
  //AsyncStorage.clear()
  return (
    <NavigationContainer>
      { user == false ?
        <AuthStackScreen />
        :
        <BuyerDashboardStackScreens />
      }

    </NavigationContainer>
  );
};

我使用 AsyncStorage 更新 app.js 中的状态。

1 个答案:

答案 0 :(得分:0)

如您所知,AsyncStorage 是异步的,用户一开始为 false,状态未加载到状态。您应该设置一个加载状态,直到状态未从 AsyncStorage 加载为止,您才会显示启动画面。登录时,根据响应设置用户状态。

const [user, setUser] = useState(false)
const [role, setRole] = useState('seller')
const [isLoading, setIsLoading] = useState(true)
...
const getKeysData =() => {
  // wait for storage data
  // setUser
  setIsLoading(false)
}
...
if(isLoading) return <Loader />
return <Navigation.../>