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

标签 javascript reactjs react-hooks

我试图获取用户信息并将其显示到页面上,但是当我转到该页面时,它完全是空白的,并且有错误提示无法读取为空的属性。所以我在应该获取的时候放置了 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/

相关文章:

javascript - 我可以在功能组件中使用什么来实现与 componentDidMount 相同的行为?

javascript - 将 "http://"添加到尚未包含 "http://"的 URL

javascript - Kendo - 如何从 View 中关闭模式窗口

javascript - AOS(滚动动画)在 React js 中不起作用

javascript - API 数据未输出 | react 、Redux

javascript - 当我尝试部署 React heroku 应用程序时出现无效的主机 header 错误

javascript - d'n'd 后动态更改 css 文件中的位置属性

javascript - 从组件中获取内容

javascript - react 保存使用重新渲染组件选择文本的可能性

javascript - 对象可能是 'null' : TypeScript, React useRef & Formik innerRef