【问题标题】:AboutHeader.jsx:21 Uncaught TypeError: this.setState is not a functionAboutHeader.jsx:21 Uncaught TypeError: this.setState is not a function
【发布时间】:2017-02-25 01:47:48
【问题描述】:

我正在尝试进行状态更改,这将在 setTimeout 之后更改 className,但是,我不断收到“AboutHeader.jsx:21 Uncaught TypeError: this.setState is not a function”我尝试绑定(this)但它仍然无法正常工作。 从“反应”导入反应;

require('../../stylesheets/component/AboutHeader.scss');

导出默认类 AboutHeader 扩展 React.Component {

constructor() {
    super()
this.timeDelay = this.timeDelay.bind(this);
    this.state = {
        class: "about-header-wrapper-hidden"
    }
}

componentDidMount() {
console.log("mounted");
    this.timeDelay();
}

时间延迟(){ setTimeout(function updateState(){this.setState({class: "about-header-wrapper"})}, 1000); console.log("timeDelay 工作"); }

render() {
    return (
        <section className={this.state.class}></section>
    )
}

}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你必须在setTimout().bind(this)Here's your code in JSBin 与绑定 this。如果删除它,则会引发错误。

    setTimeout(function updateState() {
      this.setState({ class: "about-header-wrapper" })
    }.bind(this), 1000); 
    

    【讨论】:

    • 谢谢。那行得通。我知道我必须绑定“this”,但我一直失败。非常感谢。
    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2014-08-15
    • 2021-12-16
    • 2018-04-20
    • 2017-04-13
    相关资源
    最近更新 更多