如何使用 usestate() 进行验证?

How do I make a validation with usestate()?

所以我得到了

  const [Error, setError] = useState("");

我想要这样,如果 updateDeveloper 提交正确,下面应该有一个绿色的确认文本。

const updateDeveloper = (id) => {
  Axios.put(`${url}/update`, { slack_id: newSlackID, id: id }).then(
    (response) => {
      setdeveloperList(
        developerList.map((val) => {
          return val.id === id
            ? {
                id: val.id,
                slack_id: newSlackID,
                name: val.name,
                selected: val.selected,
                absent: val.absent
              }
            : val;

          
        })
      );
    }
  );
  };

单击按钮将更新一个值。我需要它,以便在单击该按钮时,updateDeveloper 可以正常工作并给出 useState“已正确提交!”我已经有了这样的东西

<button onClick={() => { updateDeveloper(val.id); }}>Update</button>
<h1>{updateDeveloper ? {Error} : {NoError}}</h1>

我认为添加 try/catch 就足以满足您在此处尝试执行的操作。您还应该考虑添加加载状态。查看以下内容:

  const [isLoading, setIsLoading] = useState();
  const [errorMessage, setErrorMessage] = useState();
  const [successMessage, setSuccessMessage] = useState();

  const updateDeveloper = async (id) =>  {
      try{
         setIsLoading(true);            
         setSuccessMessage('');
         setErrorMessage('');

         // Call your API
         const response = await Axios.put(`${url}/update`, { slack_id: newSlackID, id: id });
         
         // handle the response
         setdeveloperList(...)
    
        // at this point you're successful and can do something like
        setSuccessMessage(`successfully updated developer ${id}`);
  
      } catch (err) {
           setErrorMessage('something went wrong');
      } finally {
           setIsLoading(false);
      }
   }

   return (
       <button onClick={() => { updateDeveloper(val.id); }}>Update</button>

       { errorMessage && <h1>{ errorMessage }</h1> }

       { successMessage && <h1>{ successMessage }</h1> }
   )