Javascript 有人能帮我吗?Can';在反应中没有发现问题
我试图在我的手机视图中制作一个倒计时时钟。但我似乎无法让数字正常工作,我的包装无法连接。 希望有人能看到我该做什么。我对Javascript和它的一切都很陌生 代码:Javascript 有人能帮我吗?Can';在反应中没有发现问题,javascript,reactjs,Javascript,Reactjs,我试图在我的手机视图中制作一个倒计时时钟。但我似乎无法让数字正常工作,我的包装无法连接。 希望有人能看到我该做什么。我对Javascript和它的一切都很陌生 代码: import React,{Component,Fragment,useState}来自“React”; const MobileView=()=>{ 类包装器扩展组件{ 构造函数(){ 超级(); this.state={}; } componentDidMount(){ 这个.startInterval(); } startI
import React,{Component,Fragment,useState}来自“React”;
const MobileView=()=>{
类包装器扩展组件{
构造函数(){
超级();
this.state={};
}
componentDidMount(){
这个.startInterval();
}
startInterval=()=>{
常数秒=1000;
常数分钟=秒*60;
常数小时=分钟*60;
常数天=小时*24;
设x=setInterval(函数(){
document.getElementById(“天”).innerText=“00”;
}(二),;
};
}
返回(
倒计时
-
天
-
小时
-
分钟
-
秒
);
};
导出默认MobileView;
您似乎在混合一些概念:
- 您正在功能组件内创建一个不使用的类组件
- 您正在尝试直接更新DOM,而不是使用状态
- 在类和功能组件之间进行选择
- 相应地设置您的状态
- 开始一个每隔X秒更新一次状态的间隔
- 清除卸载组件时的间隔
- 在渲染函数中使用状态值
import React, { useEffect, useState } from "react";
// 1. Choose between a class and a functional component
export const MobileView = () => {
// 2. Setup your state accordingly
const [secondsElapsed, setSecondsElapsed] = useState(0);
const timer = () => {
setSecondsElapsed(secondsElapsed + 1);
};
useEffect(() => {
// 3. Start an interval that will update the state every X second
const interval = setInterval(timer, 1000);
// 4. Clear the interval when the component is unmounted
return () => clearInterval(interval);
});
return (
<div className="wrapper">
<header className="Appheader">
<h1 id="head">Countdown</h1>
</header>
<div id="list">
<ul>
<li>
<span></span>
{secondsElapsed} // 5. Use your state value in the render function
</li>
</ul>
</div>
</div>
);
};
import React,{useffect,useState}来自“React”;
// 1. 在类和功能组件之间进行选择
导出常量MobileView=()=>{
//2.相应地设置您的状态
const[secondsElapsed,setSecondsAppeased]=使用状态(0);
常量计时器=()=>{
设置秒已过(秒已过+1);
};
useffect(()=>{
//3.开始每隔X秒更新一次状态的间隔
常数间隔=设置间隔(计时器,1000);
//4.清除卸载组件时的间隔
return()=>clearInterval(interval);
});
返回(
倒计时
-
{secondsElapsed}//5.在渲染函数中使用您的状态值
);
};
此外,我建议将useCallback和依赖项添加到useEffect中
const timer = useCallback(() => {
setSecondsElapsed(secondsElapsed => secondsElapsed + 1);
}, []);
useEffect(() => {
// 3. Start an interval that will update the state every X second
const interval = setInterval(timer, 1000);
// 4. Clear the interval when the component is unmounted
return () => clearInterval(interval);
}, [timer]);
您可能希望签出,它包括使用状态更新要渲染的值。您通常不会通过
innerText
或类似方式更新值,而是通过设置状态并在JSX中引用该状态来更新。