【问题标题】:Null is not an object (evaluating 'user.foto')Null 不是对象(评估“user.foto”)
【发布时间】:2023-03-04 03:46:02
【问题描述】:

我正在尝试使用 React Native 中的 Axios 从一个从 API 接收此信息并传递给正在接收并使用该上下文的另一个组件的上下文中获取包含一些用户数据的 API。

Axios API

import axios from 'axios';

export const api = axios.create({
    baseURL: 'https://virtserver.swaggerhub.com/lucasstartab/euro-api/1.0.0'
})

上下文 API

export function AuthProvider(props) {
    const [user, setUser] = useState(null);

    async function signIn() {
        try {
            const response = await api.get('/user');
            setUser(response.data[0].userInfo);
        } catch(error) {
            console.log(error);
        }
    }

    return (
        <AuthContext.Provider value={{signIn, user}}>
            {props.children}
        </AuthContext.Provider>
    )
}

使用上下文的组件

export function UserInfo({ navigation }) {
    const {user} = useContext(AuthContext);

    return (
        <ScrollView style={styles.container}>
            <Host>
                <View style={styles.padding}>
                    <View style={styles.header}>
                        <UserPhoto imageUri={user.foto} size='BIG' border={4}/>
                        <View style={styles.ProfileAndDesc}>
                            <Text style={styles.profile}>{user.name}</Text>                
                            <Text style={styles.desc}>Filial {user.filial}</Text>
                        </View>
                    </View>

我不知道为什么会出现这个错误,我检查了 API URL,但它工作正常。错误:

在我的旅程中没有更多方法试图解决这个问题,希望得到答案,谢谢!

【问题讨论】:

  • 从外观上看,可能没有名为“foto”的对象键。如果您提供一个指向 GitHub 存储库/gist 的链接并带有最少的工作代码以便更好地分析它,那就更好了。
  • 这是我从 API url 得到的:[ { "token": "a1b2c3", "userInfo": { "name": "Lucas", "email": "lucas@startab.com.br", "password": "Senha.123", "filial": "Sudeste", "foto": "https://github.com/lucastso.png", "fotoCapa": "https://images.unsplash.com/photo-1639208067515-99bccfacb05c?ixlib=rb-1.2.1&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=687&amp;q=80" } } ]

标签: react-native axios react-context


【解决方案1】:

经过几天尝试解决,一遍遍阅读代码,我意识到我在上下文中启动了“用户”状态NULL,所以我改成了一个对象“{ }" 解决了。

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-10-20
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多