Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React中的类组件内定义方法?_Reactjs_React Lifecycle - Fatal编程技术网

Reactjs 如何在React中的类组件内定义方法?

Reactjs 如何在React中的类组件内定义方法?,reactjs,react-lifecycle,Reactjs,React Lifecycle,我用React做了一个简单的数字钟。它似乎起作用了。但是,我想在setState()中单独定义回调函数。但我犯了个错误。您知道如何在componenDidMount外部定义名为tick()的函数吗?下面是我的代码 导入“/Clock.css”; 类时钟扩展了React.Component{ 状态={date:new date()}; componentDidMount(){ 设置间隔(()=>{ this.setState({date:new date()}); }, 1000); log(“c

我用React做了一个简单的数字钟。它似乎起作用了。但是,我想在setState()中单独定义回调函数。但我犯了个错误。您知道如何在componenDidMount外部定义名为tick()的函数吗?下面是我的代码

导入“/Clock.css”; 类时钟扩展了React.Component{ 状态={date:new date()}; componentDidMount(){ 设置间隔(()=>{ this.setState({date:new date()}); }, 1000); log(“componentdidmount”); } render(){ 返回( {this.state.date.toLocaleTimeString()} ); } } 输出默认时钟;
这就是你想要的吗

tick(){
    this.interval = setInterval(() => {
        this.setState({ date: new Date() });
    }, 1000);
}

componentDidMount() {
    this.tick();
    console.log('componentdidmount');
}

componentWillUnmount(){
    clearInterval(this.interval);
}

是的,它有效!我定义了一个没有内容的随机函数,但它不工作:foo(){},我得到了以下错误:index.js:1警告:无法对未安装的组件执行React状态更新。这是一个no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务这是因为即使已卸载组件,setInterval仍将运行。那样的话。您需要在清除间隔的位置添加componenWillUnmount。我将编辑代码并在那里显示它。