react hook useState

简单计数器

 

set函数不会合并, 在使用对象和数组的时候需要手动解构

对于修改数据比较简单的情况, 推荐使用函数进行修改, 会传入先前值, 将返回值作为最新值

 

import React, { useState } from "react";

export default () => {
  const initCount = 0;
  const [count, setCount] = useState(0);
  const [dx, setDx] = useState(1);
  return (
    <div>
      <div>count: {count}</div>
      <input
        value={dx}
        type="number"
        onChange={(e) => setDx(Number(e.target.value))}
      />

      <div>
        <button
          onClick={() => {
            setCount((count) => count + dx);
          }}
        >
          add
        </button>
        <button
          onClick={() => {
            setCount(initCount);
          }}
        >
          reset
        </button>
        <button
          onClick={() => {
            setCount((count) => count - dx);
          }}
        >
          del
        </button>
      </div>
    </div>
  );
};