Javascript 正在尝试将倒计时设置为特定日期的倒计时时钟,js in react
我的setInterval函数不会在组件willMount中设置state,但我似乎不明白为什么会这样。setState返回错误不是函数。这是我迄今为止的代码,任何帮助都将不胜感激Javascript 正在尝试将倒计时设置为特定日期的倒计时时钟,js in react,javascript,reactjs,gatsby,Javascript,Reactjs,Gatsby,我的setInterval函数不会在组件willMount中设置state,但我似乎不明白为什么会这样。setState返回错误不是函数。这是我迄今为止的代码,任何帮助都将不胜感激 import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import Image from "../components/image" import SEO from "../
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
import countdown from "countdown"
class Timer extends React.Component{
constructor(props){
super(props)
let time = countdown( new Date(2021, 4, 28) );
this.state = {
timeLeft: time.toString()
}
}
componentWillMount(){
const countyCount = setInterval(function(){
let timeLeft = countdown( new Date(2020, 4, 28) );
this.setState(timeLeft.toString())
}, 1000)
}
render() {
const {timeLeft} = this.state
return <span>{timeLeft}</span>
}
}
const IndexPage = () => {
return(
<Layout>
<SEO title="Home" />
<Timer/>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
}
export default IndexPage
从“React”导入React
从“盖茨比”导入{Link}
从“./组件/布局”导入布局
从“./组件/图像”导入图像
从“./组件/SEO”导入SEO
从“倒计时”导入倒计时
类计时器扩展了React.Component{
建造师(道具){
超级(道具)
让时间=倒计时(新日期(2021,4,28));
此.state={
timeLeft:time.toString()
}
}
组件willmount(){
const countyCount=setInterval(函数(){
让timeLeft=倒计时(新日期(2020年4月28日));
this.setState(timeLeft.toString())
}, 1000)
}
render(){
const{timeLeft}=this.state
返回{timeLeft}
}
}
常量索引页=()=>{
返回(
欢迎来到你的新盖茨比网站
现在去建造一些伟大的东西
转到第2页
)
}
导出默认索引扩展
您使用的是更改范围的功能,而不是为此设置键。设置状态
。正确的方法是:
const countyCount = setInterval(() => {
let timeLeft = countdown( new Date(2020, 4, 28) );
this.setState({timeLeft: timeLeft.toString() })
}, 1000)
您使用的是更改范围的功能,而不是为此设置键。设置状态
。正确的方法是:
const countyCount = setInterval(() => {
let timeLeft = countdown( new Date(2020, 4, 28) );
this.setState({timeLeft: timeLeft.toString() })
}, 1000)
完美,我还需要使用箭头函数,所以这是正确绑定的。太棒了,谢谢你,我还需要使用箭头函数,所以这是正确绑定的。太棒了,谢谢