React Native安全存储在重新加载后未正确存储对象

xwmevbvl  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(50)

我正在学习react native,并试图弄清楚SecureStore。为什么当我登录并成功将用户令牌存储在SecureStore中时,如果我使用“RR”重新加载屏幕,就无法再次使用它。当我更改代码时,它也会发生同样的事情。
当我记录用户对象console.log(user)时,我看到了它,但我不能使用console.log(user.token)来使用它。它显示为undefined?如果我json.parse用户对象,它工作正常,但我最初登录时不需要解析它。这里的交易是什么?我如何在不解析它的情况下继续使用对象?
下面是AuthProvider.js
[AxiosError:请求失败,状态代码401]

login: (email, password) => {
                setIsLoading(true);
                axiosConfig.post('login', {
                    email,
                    password,
                    device_name: 'mobile'
                })
                    .then(response => {
                        const userResponse = {
                            token: response.data.token,
                            id: response.data.user.id,
                            name: response.data.user.name,
                            email: response.data.user.email,
                            avatar: response.data.user.avatar_url,
                        };

                        // communicate with backend and store token in secure store
                        setUser(userResponse);
                        setError(null);
                        SecureStore.setItemAsync('user', JSON.stringify(userResponse))
                        setIsLoading(false);
                    }).catch(error => {
                        // If the user haven't confirm the code. Show button to re-send the link
                        if(error.response.data.has_link){
                            setHasLink(true)
                        }
                        setError(error.response.data.message)
                        setIsLoading(false);
                });
            },

字符串
下面是HomeStreen.jsx

axiosConfig.defaults.headers.common[
            'Authorization'
            ] = `Bearer ${user.token}`;

        axiosConfig
            .get(`/my-animals?page=${page}`)
            .then(response => {
                // console.log(response.data);
                if (page === 1) {
                    setAnimals(response.data.data);
                } else {
                    setAnimals([...data, ...response.data.data]);
                }

                if (!response.data.next_page_url) {
                    setIsAtEndOfScrolling(true);
                }

                setIsLoading(false);
                setIsRefreshing(false);
            })
            .catch(error => {
                console.log(error);
                setIsLoading(false);
                setIsRefreshing(false);
            });

vzgqcmou

vzgqcmou1#

明确我自己的问题。我添加了一个条件来检查useEffect钩子中的用户对象,然后在将其传递到axios之前解析该对象。

useEffect(() => {
    if(user){
        let userObj = JSON.parse(user);
        setUser(userObj);
    }
},[]);

字符串

相关问题