© Bohua Xu

useState

Jun 16, 2021 · 17min

useState

import { useState } from 'react';

export default function RequestTracker() {
  const [pending, setPending] = useState(0);
  const [completed, setCompleted] = useState(0);

  async function handleClick() {
    setPending(pending + 1);            //
    await delay(3000);
    setPending(pending=>pending - 1);
    setCompleted(completed + 1);
  }
   /* setPending(pending=>pending + 1);   //error
    await delay(3000);
    setPending(pending - 1); 不会用到上一个的返回值的   还会以为是原来的值直接减去返回结果为-1     !important  */  
  return (
    <>
      <h3>
        Pending: {pending}
      </h3>
      <h3>
        Completed: {completed}
      </h3>
      <button onClick={handleClick}>
        Buy     
      </button>
    </>
  );
}

function delay(ms) {
  return new Promise(resolve => {
    console.log(resolve)
    setTimeout(resolve, ms);
  });
}

import { useState } from 'react';

export default function RequestTracker() {
  const [pending, setPending] = useState(0);
  const [completed, setCompleted] = useState(0);

  async function handleClick() {
    setPending(pending + 1);            //
    await delay(3000);
    setPending(pending=>pending - 1);
    setCompleted(completed + 1);
  }
   /* setPending(pending=>pending + 1);   //error
    await delay(3000);
    setPending(pending - 1); 不会用到上一个的返回值的   还会以为是原来的值直接减去返回结果为-1     !important  */  
  return (
    <>
      <h3>
        Pending: {pending}
      </h3>
      <h3>
        Completed: {completed}
      </h3>
      <button onClick={handleClick}>
        Buy     
      </button>
    </>
  );
}

function delay(ms) {
  return new Promise(resolve => {
    console.log(resolve)
    setTimeout(resolve, ms);
  });
}

CC BY-NC-SA 4.0 2021-PRESENT © Bohua Xu