javascript - 在箭头函数中调用 setState 不会改变状态?

标签 javascript reactjs

在我的程序中,我必须在箭头函数中调用 setState。该函数应将 isSummaryAccordionActive 的状态设置为 true,以便可以调用另一个函数。但是,当我在箭头函数中设置状态时,状态不会改变。它在控制台中仍然显示为 false。

下面是代码:

    class TabMenuButtons extends Component {
        constructor(props) {
            super(props);
            this.state = {
                rendersummaryAccordions: false,
                renderservicesAccordions: false,
                rendertravelAccordions: false, 
                renderratesAccordions: false, 


//These variables used for other components to detect which component is currently rendered ("Active")
                isSummaryAccordionActive: false, 
                isServicesAccordionActive: false, 
                isTravelAccordionActive: false, 
                isRatesAccordionActive: false, 

            };

        }




    //The Summary Button onClick calls this function to set the state of the summaryAccordionDetector variable
    setStateisSummaryAccordionsActive = () => {
        this.setState({isSummaryAccordionActive: true})
        this.callSummaryAccordionsLogicGate();
        //WHERE THE STATE IS READING AS FALSE IN THE CONSOLE*****
        console.log(this.state.isSummaryAccordionActive)
        console.log("setStateisSummaryAccordionsActive Was called")
    }

    //Then the function above  calls this function that checks if the summaryAccordionDetector variable is really true 
    callSummaryAccordionsLogicGate = () => {
        if (this.state.isSummaryAccordionActive) {
           this.summaryAccordionsLogicGate();

        }
        else {
            // this.setState({isSummaryAccordionActive: false})
            console.log("callSummaryAccordionsLogicGate found that the summary accordion wasn't active")
        }
    }

    //If the function above verifies that the summaryAccordionDetector is really true it calls this function which renders the summary accordion
       summaryAccordionsLogicGate = () => {
            this.setState({rendersummaryAccordions: true});
            console.log("summaryAccordionsLogicGate was called, render the summary accordion")
    } 

    //   servicesAccordionsLogicGate = () => {
    //     this.setState({renderservicesAccordions: true});
    //     console.log("servicesAccordionsLogicGate was called")

    //   } 

    //   ratesAccordionsLogicGate = () => {
    //     this.setState({renderratesAccordions: true});
    //     console.log("ratesAccordionsLogicGate was called")

    //   } 

    //   travelAccordionsLogicGate = () => {
    //     this.setState({rendertravelAccordions: true});
    //     console.log("travelAccordionsLogicGate was called")

    //   } 



        render() {

            let summaryAccordionPlaceHolder = null
            let servicesAccordionPlaceHolder = null
            let ratesAccordionPlaceHolder = null
            let travelAccordionPlaceHolder = null

            this.state.rendersummaryAccordions ? summaryAccordionPlaceHolder = <SummaryAccordions/> : summaryAccordionPlaceHolder = null;
            this.state.renderservicesAccordions ? servicesAccordionPlaceHolder = <ServicesAccordions/> : servicesAccordionPlaceHolder = null;
            this.state.renderratesAccordions  ? ratesAccordionPlaceHolder = <RatesAccordions/> : ratesAccordionPlaceHolder = null;
            this.state.rendertravelAccordions  ? travelAccordionPlaceHolder = <TravelAccordions/> : travelAccordionPlaceHolder = null;

            return (
                <div>
                    <center>
                        <table cellspacing="30px">
                            <tr>
                                <td>
                                <Button label="ITEM" icon="pi pi-home"  className="TabMenuButtons" onClick={this.setStateisSummaryAccordionsActive}   style={{marginRight:'.25em', borderRadius: '8%',  backgroundColor: "#1c479c" }}></Button>
                                </td>
                                <td>
                                <Button label="ITEM" icon="pi pi-users"  className="TabMenuButtons" onClick={this.servicesAccordionsLogicGate}    style={{marginRight:'.25em', borderRadius: '8%',  backgroundColor: "#1c479c"}}></Button>
                                </td>
                                <td>
                                <Button label="ITEM" icon="pi pi-cloud"  className="TabMenuButtons" onClick={this.travelAccordionsLogicGate}  style={{marginRight:'.25em', borderRadius: '8%',  backgroundColor: "#1c479c"}}></Button>
                                </td>
                                <td>
                                <Button label="ITEM" icon="pi pi-money-bill" className="TabMenuButtons" onClick={this.ratesAccordionsLogicGate}   style={{marginRight:'.25em', borderRadius: '8%', backgroundColor: "#1c479c"}}></Button>
                                </td>
                            </tr>
                        </table>
                    </center>
                     <tr>

                        {/* EDIT THIS to become dynamic */}
                        <td className="StaticTextBelowTabView"><h1>  ITEM: <em>$67,000.00 </em></h1> </td>
                        <td className="StaticTextBelowTabView"><h1> ITEM: <em>$5,000.00</em>  </h1></td>
                        <td className="StaticTextBelowTabView"><h1> ITEM: <em>$54,406.00</em> </h1></td>
                        <td className="StaticTextBelowTabView"><h1>  ITEM: <em>1,000</em> </h1></td>
                        <td className="StaticTextBelowTabView"><h1> ITEM: <em>20.00%</em></h1></td>
                    </tr>
                    {ratesAccordionPlaceHolder}
                    {servicesAccordionPlaceHolder}
                    {travelAccordionPlaceHolder}
                    {summaryAccordionPlaceHolder}
                </div>
            );
        }

    }

我是reactJS新手,我的逻辑有什么根本性的错误吗?

编辑:谢谢大家的详细回复!在你们都提到之前我真的不知道状态。看来我以后得仔细阅读 API 引用了。

最佳答案

您需要了解的是,this.setState 是一个异步操作,它以稍后的时间间隔在幕后发生,因此无法预测状态何时会更新。这就是为什么当您调用 callSummaryAccordionsLogicGate 时,isSummaryAccordionActive 的值仍然是 false

这是一个可能的解决方案,


    setStateisSummaryAccordionsActive = () => {

      // Get the original value before setting the state
      const isSummaryAccordionActive=this.state.isSummaryAccordionActive;

      this.setState({isSummaryAccordionActive: true})

      // Pass the negation of the original value to the "callSummaryAccordionsLogicGate" function
      this.callSummaryAccordionsLogicGate(!isSummaryAccordionActive);

    }

    // Check with the parameter "isSummaryAccordionActive" which will have the correct value you expect
    callSummaryAccordionsLogicGate = (isSummaryAccordionActive) => {
      if (isSummaryAccordionActive) {
         this.summaryAccordionsLogicGate();

      }
      else {
          // this.setState({isSummaryAccordionActive: false})
          console.log("callSummaryAccordionsLogicGate found that the summary accordion wasn't active")
      }

关于javascript - 在箭头函数中调用 setState 不会改变状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57223619/

相关文章:

javascript - ReactJS 样式组件中的响应式 Prop

reactjs - @azure/storage-blob 的 BlockBlobClient.uploadData 默认使用什么 HTTP 动词?

reactjs - 在 React Native 中的 const 中插入 if/else 语句的正确方法?

node.js - 启动前从文件夹中读取文件

javascript - React 16 中生命周期钩子(Hook)贬值的主要原因

javascript - 如何使图像功能类似于文件输入字段的 "browse"按钮?

javascript - cypress xhr 请求重试 ontimeout

javascript - 刷新页面显示找不到文件错误如何使用 [angular js + NodeJS/ExpressJS] 解决

javascript - 测试以 en-us utf8 排序的字符串时的 localeCompare

javascript - 如何将 javascript 变量放入 javascript 数组中?