【问题标题】:Why do you have to parse the function call in a function during componentDidMount()?为什么必须在 componentDidMount() 期间解析函数中的函数调用?
【发布时间】:2019-11-05 17:16:44
【问题描述】:

我正在处理 react Doc 上的状态和生命周期页面。为什么我必须在解析函数中调用函数?

我尝试删除已解析的函数并仅调用 this.tick() 但它不起作用。

class Clock extends React.Component{
    constructor(props){
        super(props);
        this.state = {date: new Date()};
    }

    componentDidMount(){
        this.timerID = setInterval(()=>this.tick(), 1000)
    }

    componentWillUnmount(){
        clearInterval(this.timerID)
    }

    tick(){
        this.setState({
            date: new Date()
        })
    }

    render(){
        return (
                <h1>{new Date().toLocaleTimeString()} </h1>
        );
    }
}

【问题讨论】:

  • 我不确定我是否理解您的问题,但如果您要问的话,您可以使用setInterval(this.tick, 1000)。

标签: javascript reactjs function components document


【解决方案1】:

因为您需要传递对要执行的函数的引用,如果您传递this.tick() 是对要执行的函数的调用,您可以传递给this.tick,这也应该可以工作

【讨论】:

  • 如果你只是传递 setInterval(this.tick, 1000) ,调用上下文 this 将会丢失,它不会工作。这就是为什么您需要传递一个胖箭头函数,该函数捕获并保留this。 `
  • @LogiGunaratnam 当谈到 JS 基础知识时,MDN 通常是:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @IvanKoshelev 你是对的,我的错我忘了它是不是箭头函数的 componentdidmount 所以这个上下文丢失了
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 2021-11-03
  • 2016-08-26
  • 2020-11-15
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多