简体   繁体   English

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

[英]how to update the state of app.js using other component in react native?

I'm using native-CLI to build a react-native app.我正在使用本机 CLI 构建 react-native 应用程序。 Everything is working fine, but when I log in to the user through API, I receive token and other values.一切正常,但是当我通过 API 登录用户时,我收到了令牌和其他值。 I set them in AsyncStorage and it should jump to the buyer dashboard screen but it can't but when I refresh the app then it goes to the buyer dashboard.我将它们设置在 AsyncStorage 中,它应该跳转到买家仪表板屏幕,但它不能,但是当我刷新应用程序时,它会转到买家仪表板。 Basically, it's not refreshing the app.js after pressing the login button it should refresh the app.js also.基本上,按下登录按钮后它不会刷新 app.js,它也应该刷新 app.js。

LoginButtonCode登录按钮代码

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应用程序.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>
  );
};

I use AsyncStorage to update the state in app.js.我使用 AsyncStorage 更新 app.js 中的 state。

As you know the AsyncStorage is async, the user is false at the beginning and the state is not loaded to the state.如您所知, AsyncStorage是异步的,用户在开始时为 false,并且 state 未加载到 state。 You should set a loading state and until the state is not loaded from the AsyncStorage you show a splash screen.你应该设置一个加载 state 并且直到 state 没有从AsyncStorage加载你显示一个启动屏幕。 When you login, set the user state from the response.登录时,从响应中设置用户 state。

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.../>

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

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