最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why do I have to click twice for an event in react js - Stack Overflow

programmeradmin3浏览0评论
var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj++)
}
function minus() {
    setBroj(broj--)
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

when i click first time nothing just after second time work every 2 time ( onclick ) work

var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj++)
}
function minus() {
    setBroj(broj--)
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

when i click first time nothing just after second time work every 2 time ( onclick ) work

Share Improve this question edited Mar 20, 2021 at 13:44 Tuzi asked Mar 20, 2021 at 13:42 TuziTuzi 1601 gold badge1 silver badge14 bronze badges 3
  • I'm surprised it works the second time. Doh! I get why now. No re-render means the same broj variable is used the second time (and by then it's been updated, by the first click). – T.J. Crowder Commented Mar 20, 2021 at 13:44
  • 2 Does this answer your question? ReactJS post increment does not work in setState – jonrsharpe Commented Mar 20, 2021 at 13:45
  • 1 Side note: Use const for what you get from useState, not var or let. That can help you avoid direct mutation (of primitives, anyway). (Side note 2: Never use var. It has no place in modern JavaScript. :-) ) – T.J. Crowder Commented Mar 20, 2021 at 13:48
Add a ment  | 

3 Answers 3

Reset to default 5

When you set the state value with setBroj(broj++) it doesn't change the state with broj + 1 value because ++ affects after the code is executed. You should use setBroj(broj + 1) instead.

var [broj, setBroj] = useState(0);
function plus() {
  setBroj(broj + 1);
}
function minus() {
  setBroj(broj - 1);
}
return (
  <div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
  </div>
);

That's because you're updating state the wrong way. You're mutating the state directly using ++ and -- operators which you shouldn't. Following is the correct way :-

var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj=>broj+1)
    //setBroj(broj+1) - this will also work.
}
function minus() {
    setBroj(broj=>broj-1)
   //setBroj(broj-1) - this will also work.
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

This is because you post-increment and post-decrement.

Write setBroj(broj + 1) and setBroj(broj - 1)

Now you could pre-increment and pre-decrement but please don't. You don't need to mutate that variable.

发布评论

评论列表(0)

  1. 暂无评论