簡體   English   中英

刷新 React 中的特定組件

[英]Refresh specific component in React

我在 React 中使用功能組件,並在單擊按鈕后嘗試重新加載組件。


  import { useCallback, useState } from 'react';

  const ProfileLayout = () => {
  const [reload, setReload] = useState(false);

  const onButtonClick = useCallback(() => {
  setReload(true);
  }, []);

  return (
    {reload && (
        <ProfileDetails />
    )}
    <Button onClick={onButtonClick} />
  );

  };
export default ProfileLayout;

頁面加載后我無法再次看到該組件。 注意:我不想使用window.location.reload();

如果需要強制刷新,最好使用數字而不是 boolean。

const ProfileLayout = () => {
  const [reload, setReload] = useState(0);

  const onButtonClick = useCallback(() => {
    setReload(p => p+1);
  }, []);

  return (
    {Boolean(reload) && (
        <ProfileDetails />
    )}
  );

  };

注意:我不想使用window.location.reload();

這很好,因為這不是在 React 中執行此操作的正確方法。 強制瀏覽器重新加載將丟失所有組件或全局 state。

強制組件渲染的正確方法是調用this.setState()或調用this.forceUpdate()

重新加載組件是什么意思? 您想重新渲染它還是想讓組件再次獲取數據? 喜歡“刷新”?

無論如何,您的組件的編碼方式<ProfileDetails />組件不會出現在第一次渲染中,因為您正在執行reload && <ProfileDetails /> ,但reload最初是錯誤的。 當您單擊該按鈕時,會出現 ProfileDetails,但再次單擊該按鈕不會有任何效果,因為reload已設置為true

如果要刷新組件使用的數據,則需要實現觸發數據獲取的回調。

作者澄清后編輯

const ProfileContainer = (props) => {
  
  // initialProfile is the profile data that you need for your component. If it came from another component, then you can set it when the state is first initialized.

  const [ profile, setProfile ] = useState(props.initialProfile);

  const loadProfile = useCallback( async () => {
    // fetch data from server
    const p = await fetch('yourapi.com/profile'); // example
    setProfile(p);
  }

  return (<><ProfileDetails profile={profile} /> <button onClick={loadProfile} /></>)

}

在組件中加載數據的替代方法

const ProfileContainer = (props) => {
 
  const [ profile, setProfile ] = useState(null);

  const loadProfile = useCallback( async () => {
    // fetch data from server
    const p = await fetch('yourapi.com/profile'); // example
    setProfile(p);
  }

  useEffect(() => loadProfile(), []); // Empty dependency so the effect only runs once when component loads.
  

  return (<>
            { /* needed since profile is initially null */ 
              profile && <ProfileDetails profile={profile} /> 
            } 

             <button onClick={loadProfile} />
           </>);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM