【问题标题】:Warning: Cannot update a component from inside the function body of a different component. (React Native)警告:无法从不同组件的函数体内更新组件。 (反应原生)
【发布时间】:2021-02-06 19:49:49
【问题描述】:

我是 react native 和 javascript 的新手。试图在初始化页面上使用身份验证流来查看用户是否为登录,然后将它们重定向到相应的页面。当用户登录并导航到另一个页面时会显示该消息。

错误信息,

这是验证页面上使用的代码。

    import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { FontAwesome5 } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import styles from './styles';

import { isSignedIn, getUserType } from '../../services/auth';

export default function(){

    const navigation = useNavigation()

    async function goToLoginOng(){
        navigation.navigate('Login', {
            userType: 'ong',
            route: 'sessions'
        })
    }
    async function goToLoginUser(){
        navigation.navigate('Login', {
            userType: 'user',
            route: 'userlogin'
        })
    }

    async function userisLogged() {
        if (isSignedIn){
            const userType = getUserType();
            if (userType === 'user'){
                navigation.navigate('Incidents')
            }
            else {
                navigation.navigate('Profile')
            }
        }
    }

    userisLogged();

    return(
        <View style={styles.container}>
            <Text style={styles.bigQuestion} >Quem é você?</Text>
            <TouchableOpacity style={styles.box} onPress={goToLoginUser}>
                <FontAwesome5 name='user' size={60} color='#FFF' style={styles.iconStyle} />
                <Text style={styles.title}>Pessoa</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.box} onPress={goToLoginOng}>
                <FontAwesome5 name='users' size={60} color='#FFF' style={styles.iconStyle} />
                <Text style={styles.title}>ONG</Text>
            </TouchableOpacity>
        </View>
    )
}

这里是我使用的身份验证函数。

    import React from 'react';
import { AsyncStorage } from 'react-native';

export const isSignedIn = async() => {
    const response =  await AsyncStorage.getItem('userToken')
    if (response !== null){
        return true
    }
    else {
        return false
    }
}

export const getUserType = async () => {
    const response =  await AsyncStorage.getItem('userType')
    return response;
}

这么说,如果你能提出改进的方法,或者其他最好的方法,我会提前感谢。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    我认为问题在于userisLogged() 是直接在功能组件内部触发的。

    这意味着每当呈现此身份验证页面时都会触发userisLogged()

    所以这个函数在页面初始渲染的时候触发一次。

    这可以通过使用useEffect钩子来实现。

    useEffect(() => {
       userisLogged()
    }, [])
    

    以上代码等于类组件中的componentDidMount()

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2020-11-06
      • 2020-11-08
      相关资源
      最近更新 更多