Home  >  Q&A  >  body text

Method to stop switching between true/false when the value does not need to change

<p>I have a simple true/false toggle function: </p> <pre class="brush:php;toolbar:false;">import {useState} from 'react' const [ isTrue, setIsTrue] = useState(true) function handleSwitcher(){ {isTrue ? setIsTrue(false) : setIsTrue(true)} } <button onClick={()=>{ handleSwitcher() console.log(isTrue) }}> set to true </button> <button onClick={()=>{ handleSwitcher() console.log(isTrue) }}> set to false </button></pre> <p>If we click on these two buttons, it will always present the opposite result of true or false. What I need is that if the value of isTrue is false and I click the "Set to False" button, it does not change the value of isTrue to true. Likewise, for the "Set to True" button, it should not change the value of isTrue to false when the value is true. </p>
P粉957723124P粉957723124404 days ago444

reply all(1)I'll reply

  • P粉165823783

    P粉1658237832023-08-15 18:56:53

    You don't need a handleSwitcher, just set the desired value when the button is clicked and then it will do exactly what you want

    import {useState} from 'react'
    const [ isTrue, setIsTrue] = useState(true)
    
    <button onClick={()=>{
        setIsTrue(true)
        console.log(isTrue)
    }}>
       设置为true
    </button>
    
    <button onClick={()=>{
        setIsTrue(false)
        console.log(isTrue)
    }}>
       设置为false
    </button>

    reply
    0
  • Cancelreply