我有一个MERN Web应用程序,我正在学习React Hooks。
我想做的是:在我的Redux中访问各州。
当我刷新页面时,错误:TypeError: Cannot read property '_id' of null
当我清楚地看到redux开发工具中的状态时,我无法访问它。我尝试过console.log(auth.isAuthenicated)
,但它返回null
。但是,当我执行console.log(auth)
时,它会返回[object,object]
。这让我很困惑,因为我进不去。
目前,我正在研究并将研究反应持久性。我想知道是否有人可以在没有反应的情况下帮助我解决问题,或者解释为什么使用它可能是个好主意。
我的redux:
token(pin):"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlNDFmYTNhOWIwZjk0NmU5N2Q5MmY4MiIsImlhdCI6MTU4Mzk0NzA5MSwiZXhwIjoxNTgzOTUwNjkxfQ.pysX20n4cxKK5NqcXPosIejSvCN3pbcSNpQvEOX9kBE"
isAuthenticated(pin):true
isLoading(pin):false
_id(pin):"5e41fa3a9b0f946e97d92f82"
name(pin):"admin"
email(pin):"admin@gmail.com"
date(pin):"2020-02-11T00:50:02.183Z"
__v(pin):0
我的代码片段:
import React, { useState, useEffect } from "react";
import { TiDelete } from "react-icons/ti";
import Restaurants from "../Restaurant/Restaurants";
import NutritionalGraphs from "../D3Graphs/NutritionalGraphs";
import { connect, useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { addItem, deleteItem } from "../../../actions/itemActions";
import IngredientsPredictions from "../Predictions/IngredientsPredictions";
import { loadUser } from "../../../actions/authActions";
import { createSelector } from "reselect";
const UserProfile = props => {
const dispatch = useDispatch();
const [newUserFavorite, setNewUserFavorite] = useState("");
const [favArray, setFavArray] = useState([]);
const tokenRecognized = useSelector(state => state.auth.token);
// const userID = useSelector(state => state.auth.user._id);
const auth = useSelector(state => state.auth);
const userStates = createSelector();
// name
// name => props.auth.user.name,
// userID => props.auth.user._id
// foodFavoritesArray => foodFavoritesArray.state.item.items
useEffect(() => {
dispatch(loadUser(tokenRecognized));
// console.log(userStates.userID);
console.log(auth.isAuthenicated);
axios
// .get(`/api/items/item/${userStates.userID}`)
.get(`/api/items/item/${auth.user._id}`)
.then(res => {
return res.data;
})
.then(json => {
setFavArray(json);
})
.catch(err => console.log(err));
}, [userStates.userID]);
console.log(favArray);
它在:.get(`/api/items/item/${auth.user._id}`):
处断开
非常感谢您的阅读。
您需要等待loadUser
操作完成,然后才能访问数据。我假设它发出一个异步请求。你需要通过两个步骤做到这一点:
useEffect(() => {
// fetch user data when component mounts
dispatch(loadUser(tokenRecognized));
}, []);
useEffect(() => {
// check if user has been fetched (will not be the case on mount)
if (auth.user) {
axios
.get(`/api/items/item/${auth.user._id}`)
.then(res => {
return res.data;
})
.then(json => {
setFavArray(json);
})
.catch(err => console.log(err));
}
}, [auth.user]); // perform this when `auth.user` changes