简体   繁体   English

奇怪的执行顺序反应

[英]Strange order of execution react

Bellow is a function, handleSubmit, which is triggered when a user clicks the submit button of my form. Bellow是一个function,handleSubmit,当用户点击我表单的提交按钮时触发。 Within this function it calls the requiredInputs function that checks if all the form values (which i have stored in state) are empty.在这个 function 中,它调用 requiredInputs function 检查所有表单值(我已经存储在状态中)是否为空。 If empty I want to set some error variables (also stored in state) to true so my program can respond accordingly.如果为空,我想将一些错误变量(也存储在状态中)设置为 true,以便我的程序可以做出相应的响应。 However the first time the user clicks submit and there are empty fields, the error variables are not updated before the if condition is checked leading to the form to be submitted.但是,当用户第一次单击提交并且有空字段时,错误变量在检查 if 条件导致表单提交之前不会更新。 Subsequent invalid submission attempts are blocked though, which means the variables are updated after the submission if check is done... any idea why this behaviour is occuring?但是,随后的无效提交尝试被阻止,这意味着如果检查完成,则在提交后更新变量……知道为什么会发生这种行为吗?

Thanks谢谢

function handleSubmit() {
    requiredInputs()
    if (!titleError && !classificationError && !descriptionError) {     
      ### Entering this if statement on first click of submit when above variables should be set to true
      props.submit(title,classification,description,collaborators)
      setTitle("")
      setClassification("")
      setDescription("")
      setCollaborators([])
    }
  }

function requiredInputs () {
  if (title.length<1) setTitleError(true)
  if (description.length<1) setDescriptionError(true)
  if (classification.length<1) setClassificationError(true)
}

You are trying to access state variable immediately after setting them.您尝试在设置 state 变量后立即访问它们。 Which is not possible because state updates are asynchronous.这是不可能的,因为 state 更新是异步的。 Though class based components provide setState callback like this.setState({titleError: true}, callback) , where callback will have updated state but same is not possible in functional components.尽管基于 class 的组件提供 setState 回调,例如this.setState({titleError: true}, callback) ,其中回调将更新 state 但在功能组件中不可能。 In this case, you can try to return some boolean from requiredInputs function.在这种情况下,您可以尝试从requiredInputs function 中返回一些 boolean。

 function handleSubmit() { const hasError = requiredInputs() if (hasError) return props.submit(title,classification,description,collaborators); setTitle("") setClassification("") setDescription("") setCollaborators([]) } } function requiredInputs () { let hasError=false if (title.length<1){ hasError=true setTitleError(true) } if (description.length<1){ hasError=true setDescriptionError(true) } if (classification.length<1){ hasError = true setClassificationError(true) } return hasError }

The reason behing this is that setState is asynchronous in React这样做的原因是 setState 在 React 中是异步的

setState() does not immediately mutate this.state but creates a pending state transition. setState() 不会立即改变 this.state 而是创建一个挂起的 state 转换。 Accessing this.state after calling this method can potentially return the existing value.在调用此方法后访问 this.state 可能会返回现有值。 There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.无法保证对 setState 的调用同步操作,并且可能会批处理调用以提高性能。

If you want to use the values of state just after the setState you can use the callback function in Class components but for functional components you have use useEffect hook如果您想在 setState 之后使用 state 的值,您可以在 Class 组件中使用回调 function 组件,但对于功能组件,您可以使用 useEffect 钩子

useEffect(() => {
   if (!titleError && !classificationError && !descriptionError) {     
        props.submit(title,classification,description,collaborators)
        setTitle("")
        setClassification("")
        setDescription("")
        setCollaborators([])
},[TitleError,classificationError,descriptionError])

Now you just need to call requiredInputs function现在你只需要调用 requiredInputs function

function handleSubmit() {
    requiredInputs()
  }

requiredInputs function will update the TitleError, classificationError and descriptionError which will trigger the useEffect hook and you will have your desired effect requiredInputs function 将更新 TitleError、classificationError 和 descriptionError 这将触发 useEffect 钩子,您将获得所需的效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM