状态改变时如何保持计数器值?

How to persist counter value when the state changes?

在这个组件中,当我更改状态时,它会重新分配我不想要的 counter=1。我只希望它只分配一次 counter=1,然后在重新渲染期间不再分配它。

而且,我不想使用 useState 代替 counter 来解决这个问题。


function App() {
    const [value, setValue] = useState(100);
    let counter = 1;
    return (
    <div>
    <button
        onClick={() => {
        setValue(value - 1);
        counter++;
        }}
    >
        click me
    </button>
    </div>
);
}

export default App;

您可以使用 localStorage 保存计数器:

import { useState } from "react";

function App() {
  const [value, setValue] = useState(100);
  let counter = localStorage.getItem('counter') || 1;
  return (
    <div>
      <button
        onClick={() => {
          setValue(value - 1);
          localStorage.setItem('counter', ++counter);
        }}
      >
        click me
      </button>
    </div>
  );
}

export default App;

您可以使用 useRef:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render.

function App() {
  const [value, setValue] = useState(100)
  const counter = useRef(1)
  return (
    <div>
      <button
        onClick={() => {
          setValue(value - 1)
          counter.current++
        }}
      >
        click me
      </button>
    </div>
  )
}