gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:18:22 27 4
gpt4 key购买 nike

我试图获取用户信息并将其显示到页面上,但是当我转到该页面时,它完全是空白的,并且有错误提示无法读取为空的属性。所以我在应该获取的时候放置了 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 可能会抛出错误,因此您的代码永远不会进入 then block 。您需要添加一个 catch block 并使用错误数据呈现一些 ui 或将用户重定向到其他地方或显示一个 toastr 等...如果您想显示一个 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

关于javascript - 尝试获取信息时 useEffect 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73721651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com