Javascript 如何在GatsbyJS/ReactJS中重复执行窗口函数?
我试图在创建GatsbyJS/ReactJS页面时重复执行窗口函数。这是我的密码:Javascript 如何在GatsbyJS/ReactJS中重复执行窗口函数?,javascript,reactjs,function,typeerror,gatsby,Javascript,Reactjs,Function,Typeerror,Gatsby,我试图在创建GatsbyJS/ReactJS页面时重复执行窗口函数。这是我的密码: import React, { Component } from "react"; class Example extends Component { componentDidMount() { this.Foo(); } Foo() { console.log(typeof window); if (typeof window !== "undefined") {
import React, { Component } from "react";
class Example extends Component {
componentDidMount() {
this.Foo();
}
Foo() {
console.log(typeof window);
if (typeof window !== "undefined") {
window.setTimeout(
(() => {
console.log("bar");
},
200)
)();
}
}
render(){
return {
<>
</>
}
}
}
export default Example;
import React,{Component}来自“React”;
类示例扩展组件{
componentDidMount(){
this.Foo();
}
Foo(){
控制台日志(窗口类型);
如果(窗口类型!=“未定义”){
window.setTimeout(
(() => {
控制台日志(“bar”);
},
200)
)();
}
}
render(){
返回{
}
}
}
导出默认示例;
我的问题是为什么我一直收到
TypeError:window.setTimeout(…)不是一个函数
<代码>窗口已定义,但我无法使用其任何方法。该函数将在将来修改状态,因此必须在呈现react组件后的安装阶段运行。我做错了什么?您基本上是在调用setTimeout(…)()
,这会引发错误,因为setTimeout(…)
不返回函数
window.setTimeout(
(() => {
console.log("bar");
},
200)
)();
^^
还有一对不必要的括号。您应该这样做:
window.setTimeout(() => { ... }, 200);
与问题无关,但在javascript类中,常规方法不使用大写字母;您还希望删除jsx周围的花括号或使用括号,因此
return()
而不是return{}