Javascript 在ReactJs中渲染时,react倒计时重置

Javascript 在ReactJs中渲染时,react倒计时重置,javascript,reactjs,Javascript,Reactjs,我正在创建一个游戏,用户可以点击一个按钮,因为他们可以在一个时间范围内 我已使用反应倒计时创建计时器。但当我点击按钮时,计时器会自动复位 这是我的密码 import React, { useState } from "react" import Countdown from 'react-countdown'; function App() { const [name, setName] = useState("") const [isLogi

我正在创建一个游戏,用户可以点击一个按钮,因为他们可以在一个时间范围内

我已使用
反应倒计时
创建计时器。但当我点击按钮时,计时器会自动复位

这是我的密码

import React, { useState } from "react"
import Countdown from 'react-countdown';

function App() {

  const [name, setName] = useState("")
  const [isLogin, setIsLogin] = useState(false)
  const [counter, setCounter] = useState(0)

  const submitName = () => {
    setIsLogin(true)
  }

  const updateCounter = () => {
    console.log(counter)
    setCounter(counter + 1)
  }

  return (
    <div>
      {!isLogin ? (
        <div>
          <input
            style={{ width: 300, height: 30 }}
            placeholder="Input name here"
            value={name}
            onChange={e => setName(e.target.value)}
          />
          <button
            style={{ width: 50, height: 20, background: "red" }}
            onClick={() => submitName()}
          >Go</button>
        </div>
      ) : (
          <div
            style={{ width: "100vw", height: "100vh", background: "yellow" }}>
            <Countdown date={Date.now() + 100000} />
            <h1>{name}</h1>
            <h3>Click counter: {counter} </h3>
            <button
              style={{
                width: 100,
                height: 50,
                background: "red",
                border: "none",
                borderRadius: 25,
                color: "white",
                cursor: "pointer"
              }}
              onClick={() => updateCounter()}>Click here!</button>
          </div>
        )
      }
    </div>
  );
}

export default App;
import React,{useState}来自“React”
从“反应倒计时”导入倒计时;
函数App(){
const[name,setName]=useState(“”)
const[isLogin,setIsLogin]=useState(false)
常量[计数器,设置计数器]=使用状态(0)
const submitName=()=>{
setIsLogin(真)
}
常量updateCounter=()=>{
控制台日志(计数器)
设置计数器(计数器+1)
}
返回(
{!伊斯洛金(
setName(e.target.value)}
/>
submitName()}
>去
) : (
{name}
单击计数器:{counter}
updateCounter()}>单击此处!
)
}
);
}
导出默认应用程序;
问题是当我点击按钮时,
setCounter(counter+1)
正在运行,并重新进入页面。这使计数器复位。
我知道它为什么会出现问题,但我无法修复。

您需要记忆
倒计时组件:

const CountdownWrapper = () => <Countdown date={Date.now() + 100000} />;
const MemoCountdown = React.memo(CountdownWrapper);

// usage
<MemoCountdown/>
const CountdownWrapper=()=>;
const memoccountdown=React.memo(CountdownWrapper);
//用法
之前,在每次渲染
Date.now()
时都会获得一个新值,该值会重置计时器


显然,您可以创建组件,该组件将在本地处理单击和更新状态。因此,只有带有计数器的组件才会重新渲染。退房:谢谢你的支持。还有一个问题,我如何使用setTimeout来代替react countdown?这是SO和Google中搜索最多的问题,试着查找一下,