Home  >  Q&A  >  body text

Why is the number not growing as I expected, but increasing by 2 instead of 1?

<p>I have the following code in React: </p> <pre class="brush:php;toolbar:false;">let guest = 0; functionCup() { guest = guest 1; return <h2>{guest}’s teacup</h2>; } export default function TeaSet() { return ( <> <Cup /> <Cup /> <Cup /> </> ); }</pre> <p>My desired result is:</p> <pre class="lang-none prettyprint-override"><code>The first guest’s teacup Tea cup for the 2nd guest The third guest’s tea cup </code></pre> <p>However, the actual result returned is: </p> <pre class="brush:php;toolbar:false;">The second guest’s teacup, The fourth guest’s tea cup, The 6th guest’s teacup</pre> <p>Why is the increment of <code>guest</code> 2 instead of 1 as I specified? </p>
P粉752812853P粉752812853455 days ago506

reply all(1)I'll reply

  • P粉052686710

    P粉0526867102023-08-15 14:39:27

    Global state variables may not be a viable way to achieve this goal.

    Based on what you mentioned in your question, you could try passing param as count.

    import { useEffect } from "react";
    
    const  Cup  = ({guestCount}) => {
        return 

    为第{guestCount}位客人准备的茶杯

    ; } export default function TeaSet() { return ( <> ); }

    reply
    0
  • Cancelreply