ReactJS:增量计数器保持刷新组件

ReactJS: Increment counter keeps refreshing component

所以最近我开始了一个项目来玩弄 NextJS。

我 运行 关于我的计数状态的问题:

//Core
import React, { useState, useEffect } from 'react';

//Style
import styles from './form.module.scss';

export default function Form({ placeholder }) {
  const [count, setCounter] = useState(0);

  return (
    <form>
      <input
        type='text'
        placeholder={placeholder}
        className={styles.error}
      ></input>
      <button onClick={() => setCounter(count + 1)}>{count}</button>
    </form>
  );
}

每次单击递增按钮时,这都会不断刷新我的计数状态。在不重新渲染组件的情况下进行点击增量的正确方法是什么?

我在网上找到了这样的例子: https://codesandbox.io/s/react-hooks-counter-demo-kevxp?file=/src/index.js:460-465

为什么我的计数器一直在重置,而他们的却没有?

你在 form.

里面

先用preventDefault,以免每次都提交表单

  <button
    onClick={(e) => {
      e.preventDefault();
      setCounter(count + 1);
    }}
  >
    {count}
  </button>

查看实际效果 here

您也可以将按钮的类型设置为“按钮”以防止表单提交

<button type="button" onClick={() => setCounter(count + 1)}>{count}</button>

使用 useRef,您可以在重新渲染时保持相同的数据

import React, { useState, useRef } from "react";

export const Form = () => {
  const counterEl = useRef(0);
  const [count, setCount] = useState(counterEl.current);

  const increment = () => {
    counterEl.current = counterEl.current + 1;
    setCount(counterEl.current);
    console.log(counterEl);
  };

  return (
    <>
      Count: <span>{count}</span>
      <button onClick={increment}>+</button>
    </>
  );
};

我认为这是因为您将按钮包装在表单中 默认情况下,当您在表单提交触发器中按下按钮时 然后整个页面呈现状态重置