简体   繁体   English

React Hooks:带有 onClick 的 useState 仅在单击第二次按钮后更新?

[英]React Hooks: useState with onClick only updating after the 2nd time button is clicked?

When I try to click on the button 'To/FROM selected units' the addtoproduction function is being called and data is being logged.当我尝试单击“To/FROM selected units”按钮时,正在调用 addtoproduction 函数并记录数据。 It does not work the first time I do it however the second time it does.我第一次这样做时它不起作用,但是第二次它起作用了。

I'm guessing useEffect would work because it is asynchronous, but I don't know how to write it or where to put it.我猜 useEffect 会起作用,因为它是异步的,但我不知道如何编写它或将它放在哪里。 Eventually this data will be posted to the back end of the server.最终,这些数据将被发布到服务器的后端。

please help me getting this button to console log the correct values the first time it is clicked on.请帮助我获取此按钮以在第一次单击时控制台记录正确的值。

Code:代码:

 const [AddRemoveDatabaseChanges, setAddRemoveDatabaseChanges] = useState(null)
  const [AddRemoveDatabaseMode, setAddRemoveDatabaseMode] = useState('ADD')

 const addtoproduction =  () => {

    let databaseChanges = unitTestsData.map(tests => { 
    return {
      "unit_test_id": tests.unit_test_template_id,
      "databases": tests.databases
    }
  })
  setAddRemoveDatabaseChanges(databaseChanges)

  if(AddRemoveDatabaseChanges != null && AddRemoveDatabaseMode === 'ADD'){
   
    setAddRemoveDatabaseChanges(databaseChanges)
   
    console.log('added data', AddRemoveDatabaseChanges);

  } else if (AddRemoveDatabaseChanges != null && AddRemoveDatabaseMode === 'REMOVE') {
    setAddRemoveDatabaseChanges(databaseChanges)
    console.log('removed data', AddRemoveDatabaseChanges )

  }
  }

Button:按钮:

   <div style={{width: '100%'}}>
          <Button 
          text='TO/FROM SELECTED UNIT TESTS'
          onClick={addtoproduction}

           />
        </div>
        </div>

Since the state change is Async hence we should not use the state just after setting it.由于状态更改是异步的,因此我们不应在设置后立即使用状态。 Instead use useEffect link this:-而是使用useEffect链接:-

  useEffect(() => {
   console.log(AddRemoveDatabaseChanges);
 }, [AddRemoveDatabaseChanges])

This will console the updated state and you can use the state value here to implement any logic.这将控制更新的状态,您可以使用此处的状态值来实现任何逻辑。

The problem is not about the button, it is calling the handler correctly, but your addtoproduction function should be rewritten.问题不在于按钮,而是正确调用处理程序,但您的addtoproduction函数应该被重写。 Set state functions are asynchronous, so you cannot use their result immediately after them.设置状态函数是异步的,因此您不能在它们之后立即使用它们的结果。 Here you call setAddRemoveDatabaseChanges and in the next line check for AddRemoveDatabaseChanges when it is not yet set into the state.在这里,您调用setAddRemoveDatabaseChanges并在下一行检查AddRemoveDatabaseChanges尚未设置为状态时。 As a result, it is not working as expected the first time, but the next time the state is already set and you see the console.log结果,它第一次没有按预期工作,但是下次状态已经设置并且您看到 console.log

I think this is what you are trying to achieve我认为这就是你想要实现的目标

const [AddRemoveDatabaseChanges, setAddRemoveDatabaseChanges] = useState(null)
  const [AddRemoveDatabaseMode, setAddRemoveDatabaseMode] = useState('ADD')

  useEffect(() => {
    if(AddRemoveDatabaseMode === 'ADD'){  
      console.log('added data', AddRemoveDatabaseChanges);
    } else if (AddRemoveDatabaseMode === 'REMOVE') {
      console.log('removed data', AddRemoveDatabaseChanges );
    }
  }, [AddRemoveDatabaseChanges, AddRemoveDatabaseMode]);

  const addtoproduction =  () => {
    let databaseChanges = unitTestsData.map(tests => { 
      return {
        "unit_test_id": tests.unit_test_template_id,
        "databases": tests.databases,
      }
    })
    setAddRemoveDatabaseChanges(databaseChanges);
    setAddRemoveDatabaseMode('ADD'); // Pass ADD/REMOVE depending on your call
  }

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

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