簡體   English   中英

使用 history.push() 重新渲染當前組件

[英]Using history.push() re-renders current component

我有一個從當前位置狀態獲取值並將其傳遞給子組件的組件。

interface RequestProcessingLocationState {
  request: RequestType; 
}
function RequestProcessing() { 
    const location = useLocation<RequestProcessingLocationState>();
    return (
     <div>
         <RequestDetails
             processId={location.state.request.processId}
             requestTitle={location.state.request.title}
         />
         <RequestForm request={location.state.request} />
     </div>
    ); 
}

其中一個子組件具有調用 REST 端點並處理請求的表單。

function RequestForm ({ request}: RequestFormPropsType): ReactElement {
    ... 
    const history = useHistory();
    useEffect(() => {     
        axiosInstance.get(/request/${request.id}/form) 
        .then((result) => {
             setForm(result.data);       
        }) 
        .catch((error) => {         
            console.log(error);       
     });   }, [request]);

const handleSubmit = ({ formData }: any) => { 
    axiosInstance.put(/request/process/${request.id}, formData)       
    .then(() => { 
        message.success(t("request-success")); 
        history.push("/requests); 
        })       
        .catch((error) => { 
            console.log(error.response); 
        });
};
    return ( ...)
}

問題出現在handleSubmit方法被調用的時候,特別是history.push()被執行的時候。 由於某種原因,RequestForm 組件的 useEffect() 方法再次執行,axios 調用拋出錯誤,因為請求已經被處理。

我的猜測是,當位置更改時,組件會立即更新,因為依賴項數組中的請求來自位置狀態。

有什么辦法可以避免這種行為嗎?

這是因為默認提交表單。 為了防止在您的提交函數handleSubmit出現這種情況,您必須添加event.preventDefault(); .

嘗試將第二個參數添加到 useEffect 鈎子這樣的空數組。

useEffect(() => {
    // Run! Like go get some data from an API.
  }, []);

我認為由於您的request依賴項,您不需要在useEffect傳遞依賴項,因為它是道具。 像這樣使用:

  useEffect(() => {     
    request && axiosInstance.get(/request/${request.id}/form) 
    .then((result) => {
         setForm(result.data);       
    }) 
    .catch((error) => {         
        console.log(error);
  // remove warning
  // eslint-disable-next-line react-hooks/exhaustive-deps
 });   }, []);

它只在安裝組件時調用一次

暫無
暫無

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

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