Method to stop switching between true/false when the value does not need to change
P粉957723124
2023-08-14 19:43:19
<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>
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