【问题标题】:ReactJS: Increment counter keeps refreshing componentReactJS:增量计数器不断刷新组件
【发布时间】:2021-09-16 05:12:41
【问题描述】:

所以最近我开始了一个有趣的项目来玩 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

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

【问题讨论】:

  • 该代码有什么问题?由于count 是一个状态,所以当你改变它时,React 会重新渲染它。

标签: reactjs counter increment


【解决方案1】:

你在form中。

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

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

在行动中看到它here

【讨论】:

  • 向按钮添加type="button" 也可以。当您将按钮包装到表单中时,默认类型为submit,这意味着一旦您单击按钮,它就会尝试将您的表单提交到特定的 url。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    使用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>
        </>
      );
    };
    
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2012-03-02
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 2020-09-23
        • 2021-02-26
        • 2021-11-30
        • 1970-01-01
        相关资源
        最近更新 更多