useEffect在尝试获取信息时不起作用



我试图获取用户信息并将其显示在页面上,但当我转到页面时,它完全是空白的,并且有错误表明无法读取null属性。因此,我在假设提取console.log时放了它,但它从未显示,这就是为什么我意识到useEffect中的函数没有被调用,我真的不知道为什么。


function User() {
const[userInfo, setUserInfo] = useState(null);
const {user, checkAuth} = useContext(UserContext);
const [redirect, setRedirect] = useState(false);
const params = useParams();
function logout() {
axios.post('http://localhost:3030/logout', {}, {withCredentials: true})
.then(() => {
checkAuth().catch(() => setRedirect(true));
});
}
useEffect(() => {
function getUserInfo() {
axios.get('http://localhost:3030/users/'+params.id)
.then(response => {
setUserInfo(response.data);
console.log('here'); //this never shows in the console
});
}
getUserInfo();
}, [params.id]);
if (redirect) {
return (<Navigate to={'/'} />);
}

return (
<main>
<Container>
<ContainerHeader>
<StyledHeader>Profile</StyledHeader>
{!!userInfo && !!user && parseInt(params.id) === user.id && (
<LinksRow>
<EditLinkButton to={'/profile'}><FontAwesomeIcon icon={faEdit} />  Edit</EditLinkButton>
<Button onClick={() => logout()}><FontAwesomeIcon icon={faArrowRight} />  Logout</Button>
</LinksRow>
)}
</ContainerHeader>

<Img src={ProfileImg} alt=""/>
<Name>{userInfo.first_name} {userInfo.last_name}</Name>
<Role>{userInfo.role}</Role>
<Role>{userInfo.sector}</Role>
<Labels><FontAwesomeIcon icon={faEnvelope}/> {userInfo.email}</Labels>
<Labels> <FontAwesomeIcon icon={faLocationDot} /> {userInfo.location} </Labels>
<Labels>
<Links href={userInfo.link} target="_blank"> <FontAwesomeIcon icon={faExternalLink} /> {userInfo.link}</Links>
</Labels>
<Labels> <FontAwesomeIcon icon={faCoins} /> 100 CxCoins</Labels>
<SecondHeader>Statistics</SecondHeader>
<Labels> <FontAwesomeIcon icon={faComment} /> 100 comments</Labels>
<Labels> <FontAwesomeIcon icon={faTicket} /> 100 tickets</Labels>

</Container>
</main>

);
}
export default User 

谢谢!

  1. API可能会抛出错误,因此代码永远不会进入然后的块。你需要添加一个catch块,并用错误数据渲染一些ui,或者将用户重定向到其他地方,或者显示一个烤面包机等等。如果你想显示一个ui,你可以向你的组件添加一个错误状态

  2. 在API为您获取数据之前,您的userInfo为空,因此您无法访问例如userInfo.first_name。组件抛出渲染错误,因此useEffect永远没有机会运行渲染成功后运行的效果。按照下面的代码,我等待userInfo在我访问它的任何密钥之前有一些数据

  3. 您也可以考虑将加载状态添加到组件

    function User() {      
    const[userInfo, setUserInfo] = useState(null);
    const {user, checkAuth} = useContext(UserContext);
    const [redirect, setRedirect] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(false);
    
    const params = useParams();
    function logout() {
    axios.post('http://localhost:3030/logout', {}, {withCredentials: true})
    .then(() => {
    checkAuth().catch(() => setRedirect(true));
    });
    }
    useEffect(() => {
    function getUserInfo() {
    setIsLoading(true)       axios.get('http://localhost:3030/users/'+params.id)
    .then(response => {
    setUserInfo(response.data);
    console.log('here'); //this never shows in the console
    })
    .catch(err=>setError(err?.message)) 
    .finally(() =>setIsLoading(false)) 
    }
    getUserInfo();
    }, [params.id]);
    if (redirect) {
    return (<Navigate to={'/'} />);
    }
    if (isLoading) {
    return (<Loader />);
    }
    return (
    <main>
    <Container>
    <ContainerHeader>
    <StyledHeader>Profile</StyledHeader>
    {!!userInfo && !!user && parseInt(params.id) === user.id && (
    <LinksRow>
    <EditLinkButton to={'/profile'}><FontAwesomeIcon icon={faEdit} />  Edit</EditLinkButton>
    <Button onClick={() => logout()}><FontAwesomeIcon icon={faArrowRight} />  Logout</Button>
    </LinksRow>
    )}
    </ContainerHeader>
    {error && <Error error={error}/> 
    {!error &&  Object.keys(userInfo).length>0 && (  <>
    <Img src={ProfileImg} alt=""/>
    <Name>{userInfo.first_name} {userInfo.last_name}</Name>
    <Role>{userInfo.role}</Role>
    <Role>{userInfo.sector}</Role>
    <Labels><FontAwesomeIcon icon={faEnvelope}/> {userInfo.email}</Labels>
    <Labels> <FontAwesomeIcon icon={faLocationDot} /> {userInfo.location} </Labels>
    <Labels>
    <Links href={userInfo.link} target="_blank"> <FontAwesomeIcon icon={faExternalLink} /> {userInfo.link}</Links>
    </Labels>
    <Labels> <FontAwesomeIcon icon={faCoins} /> 100 CxCoins</Labels>
    <SecondHeader>Statistics</SecondHeader>
    <Labels> <FontAwesomeIcon icon={faComment} /> 100 comments</Labels>
    <Labels> <FontAwesomeIcon icon={faTicket} /> 100 tickets</Labels>
    </>) 
    }               
    </Container>
    </main>
    );
    }
    export default User
    

将getUserInfo方法移动到userEffect钩子之外。那么它可能是工作。

最新更新