使用history.push重新渲染当前组件

问题描述

我有一个从当前位置状态获取值并将其传递给子组件的组件。

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中添加第二个参数,以钩住像这样的空数组。

ary.slice_when { |a,b| (b != a + 1) && (b != a - 1) }.map(&:first)[1..]
#=> [6,10,14,19,100,30,40]
,

我认为由于您的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
 });   },[]);

它在安装组件时只调用一次

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...