Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何使用try-catch和React-State-with-Arrow函数处理错误_Reactjs_Validation_React Redux_React 16 - Fatal编程技术网

Reactjs 如何使用try-catch和React-State-with-Arrow函数处理错误

Reactjs 如何使用try-catch和React-State-with-Arrow函数处理错误,reactjs,validation,react-redux,react-16,Reactjs,Validation,React Redux,React 16,我对React还不熟悉,我试图用React arrow函数实现一些错误验证,但一整天都没有运气。 catch可以工作,我可以打印错误,但我不知道如何将我在errorsHandler()内打印的错误链接到表单用于样式和警告的其他常量 const errorsHandler= fieldErrors => { if (fieldErrors) { fieldErrors.forEach(err => { const errorFie

我对React还不熟悉,我试图用React arrow函数实现一些错误验证,但一整天都没有运气。 catch可以工作,我可以打印错误,但我不知道如何将我在errorsHandler()内打印的错误链接到表单用于样式和警告的其他常量

  const errorsHandler= fieldErrors => {
      if (fieldErrors) {
         fieldErrors.forEach(err => {
           const errorFieldName= err.field;
           const errorDescription = err.message;
           console.log('Field',  errorFieldName, 'Description', errorDescription);
           // Field name Description name already exists
         });
       }
   };
   export const defaultGroupModel = {
       description: '',
       active: true,
       name: '',
    }
    const GroupFormModal = ({ editId, editGroup, onSave}) => {
        const [groupState, setGroupState] = useState(defaultGroupModel);

        useEffect(() => {
           if (editGroup) {
              setGroupState(editGroup);
           }
        }, [editGroup]);

        const handleChange = ({ target: { value, name} }) => {
           setGroupState({ ...groupState, [name]: value });
        };

        return ( (...) <Form onSubmit={e => onSave(e, groupState)} onReset={onReset}> (...);
    };

    const mapDispatchToProps = dispatch => ({
      onSave: (e, group) => {
        e.preventDefault();
        if (group.id) {
          dispatch(updateGroup(group));
        } else {
          dispatch(createGroup(group)).catch(error => {
            errorsHandler(error.data.fieldErrors);
          });
        }
      },
    });

    export default connect(
      mapStateToProps,
      mapDispatchToProps,
    )(GroupFormModal);
const errorsHandler=fieldErrors=>{
如果(字段错误){
fieldErrors.forEach(err=>{
常量errorFieldName=err.field;
const errorDescription=err.message;
日志('Field',errorFieldName',Description',errorDescription);
//字段名称描述名称已存在
});
}
};
导出常量defaultGroupModel={
说明:“”,
主动:对,
名称:“”,
}
const GroupFormModal=({editId,editGroup,onSave})=>{
const[groupState,setGroupState]=useState(defaultGroupModel);
useffect(()=>{
如果(编辑组){
setGroupState(编辑组);
}
}[编辑组];
const handleChange=({target:{value,name}})=>{
setGroupState({…groupState,[名称]:值});
};
返回(…)onSave(e,groupState)}onReset={onReset}>(…);
};
const mapDispatchToProps=调度=>({
onSave:(e,组)=>{
e、 预防默认值();
if(group.id){
调度(更新组(组));
}否则{
调度(createGroup(group)).catch(错误=>{
errorsHandler(error.data.fieldErrors);
});
}
},
});
导出默认连接(
MapStateTops,
mapDispatchToProps,
)(集团形式模式);
我试图创建一个[errorState,setErrorState],并在errorsHandler中使用useEffect,但得到的钩子无效。我如何使catch中的句柄与表单处于相同的上下文中


提前感谢您

这里您可以做的事情很少。首先,使用
mapDispatchToProps
包装在
调度中
操作的创建者(没有
,然后
捕获

现在,您可以设置内部
状态
,以反映这些错误

const Component = ({ updateGroup, createGroup }) =>{
    const [errors, setErrors] = useState(false)

    const onSave = (group,e) =>{
       createGroup(group)
           .then(res => console.log('everything ok'))
           .catch(err => setError(err) /* now you have the errors inside your component*/)
    }

    return <form onSubmit={ e => onSave(group,e)) }> /*...*/ </form>
}
const组件=({updateGroup,createGroup})=>{
常量[errors,setErrors]=useState(false)
const onSave=(组,e)=>{
创建组(组)
.then(res=>console.log('everything ok'))
.catch(err=>setError(err)/*现在您的组件中存在错误*/)
}
返回onSave(group,e))}>/*…*/
}

请注意,try-catch不适用于React组件,因为它们是声明性的。出于同样的目的,React有一个错误边界的概念。一定要调查一下,这是唯一的办法吗?我的意思是,是否也可以在捕获中分派errorsHandler(),我从主组件的道具中读取错误?在React nothing中,这从来不是唯一的方法。是的,您也可以使用
redux
进行操作
const Component = ({ updateGroup, createGroup }) =>{
    const [errors, setErrors] = useState(false)

    const onSave = (group,e) =>{
       createGroup(group)
           .then(res => console.log('everything ok'))
           .catch(err => setError(err) /* now you have the errors inside your component*/)
    }

    return <form onSubmit={ e => onSave(group,e)) }> /*...*/ </form>
}