首页 > 解决方案 > 条件渲染,使用超时 Invalid hook call React

问题描述

当检查为真时,我想显示下一步按钮。我收到意外令牌、无效挂钩调用等错误。请帮助我。在此先感谢。

import React from "react";
import useTimeout from "use-timeout";

class App extends React.Component {
  state = { check: true };

  handleCheck = () => {
    this.setState({ check: !this.state.check });
  };
  render() {
    useTimeout(() => {
      this.handleCheck();
    }, 10000);
    return (
      <div>
      {
       if(this.state.check){
        return <button>Next</button> 
      }
     }
      </div>
    );
  }
}
export default App;

标签: reactjstimeoutreact-hooksuse-stateconditional-rendering

解决方案


改为这样做:

<div> {this.state.check && <button>Next</button> </div>

并删除useTimeout你不需要它,你也不能使用它,因为它是一个钩子,你正在使用一个类组件。您应该onClick改为触发它,或者如果您坚持使用超时使用setTimeout,但我不建议使用该内部渲染

使用timeout这样的:

componentDidmount() {
    setTimeout(() => {
      this.handleCheck();
    }, 10000); 
}

推荐阅读