简体   繁体   English

即使第一个函数调用第二个函数,函数也不按正确顺序触发

[英]Functions not firing in correct order even though first function calls second

My aim was to use a boolean stored in state to update a dropdown menu to either show or remain hidden. 我的目的是使用存储在状态中的布尔值来更新下拉菜单以显示或保持隐藏状态。 I wrote two functions, 'toggleHander' (triggered by a click event) which toggles the boolean state and then calls the next function - 'dropdownClickHandler'. 我编写了两个函数,'toggleHander'(由click事件触发),它切换布尔状态,然后调用下一个函数 - 'dropdownClickHandler'。 'dropdownClickHandler' adds a 'show' css class (or not) dependent on the state of the boolean held in state hence updating the drop down menu. 'dropdownClickHandler'根据状态保持的布尔状态添加'show'css类(或不),从而更新下拉菜单。

My problem (I think) is that the second function ('dropdownClickHandler') is called before the first ('toggleHandler') - even though the 'toggleHandler' is directly triggered by a click event and should only call the second function after setState has completed. 我的问题(我认为)第二个函数('dropdownClickHandler')在第一个函数('toggleHandler')之前调用 - 即使'toggleHandler'由click事件直接触发,并且只应在setState之后调用第二个函数完成。 This results in a user needing to click twice before the drop down shows (instead of once). 这导致用户需要在下拉显示之前单击两次(而不是一次)。

I'm not sure if this is something to do with hoisting or the asynchronous nature of setState? 我不确定这是否与提升或setState的异步性质有关? Or perhaps something else? 或许还有其他什么?

Any help appreciated 任何帮助赞赏

FYI - I've tried changing the initial boolean state to true and the menu works. 仅供参考 - 我尝试将初始布尔状态更改为true并且菜单有效。 I just don't understand the order of function calls 我只是不明白函数调用的顺序

Codepen here: https://codepen.io/kiron/pen/vwERzP Codepen: https ://codepen.io/kiron/pen/vwERzP

Suspected offending code: 怀疑违规代码:

toggleHandler = () => {
  this.setState(
    {addClass: !this.state.addClass},
    () => console.log('in toggle', this.state),                             
      this.dropdownClickHandler()
  ); 
}


dropdownClickHandler = () => {
  console.log('in drop', this.state);
  this.state.addClass === true ? boxClass = ["dropdownContent", "dropdownContent__show"] : boxClass = ["dropdownContent"]
}   

proper syntax: 正确的语法:

toggleHandler = () => {
  this.setState(
    {addClass: !this.state.addClass},
    () => {
      console.log('in toggle', this.state),                             
      this.dropdownClickHandler()
    }
  ); 
}

but (as stated in comments) dropdownClickHandler() won't work correctly ... 但是(如评论中所述) dropdownClickHandler()将无法正常工作......

...you don't need it at all (basic conditional renderings): ......根本不需要它(基本的条件渲染):

render() {
  const boxClass = this.state.addClass ? "dropdownContent dropdownContent__show" : "dropdownContent"

  return (
    <div className={boxClass} >

or even simpler 甚至更简单

render() {
  return (
    <div className={"dropdownContent "+ this.state.addClass && "dropdownContent__show"} >

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

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