【问题标题】:react-countdown resets when rendered in ReactJsreact-countdown 在 ReactJs 中渲染时重置
【发布时间】:2021-05-12 05:43:30
【问题描述】:

我正在创建一个游戏,用户可以在一段时间内尽可能多地点击按钮。

我使用react-countdown 来创建计时器。但是当我点击一个按钮时,计时器会自动重置。

这是我的代码。

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;

问题是当我点击按钮时,setCounter(counter + 1) 正在运行并重新呈现页面。这使得计数器复位。 我知道它为什么会出现问题,但我无法修复它。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

你需要记住Countdown组件:

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

// usage
<MemoCountdown/>

事先,在每次渲染时,Date.now() 都会获得一个重置计时器的新值。

【讨论】:

猜你喜欢
  • 2019-01-08
  • 2017-11-11
  • 2016-12-30
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2015-06-05
相关资源
最近更新 更多