函数未在 setTimeout 中执行

Function is not being executed within setTimeout

本文关键字:执行 setTimeout 函数      更新时间:2023-09-26

我正在尝试将以下代码与 React Native 一起使用:

...
_getContentHeight() {
    if (this.refs.AccordionContent) {
        this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
            // Sets content height in state
            this.setState({
                height: this.props.expanded ? height : 0,
                content_height: height
            });
        });
    }
},
componentDidMount() {
    // Gets content height when component mounts
    // without setTimeout, measure returns 0 for every value.
    // See https://github.com/facebook/react-native/issues/953
    setTimeout(this._getContentHeight);
    // tried setTimeout(this._getContentHeight.bind(this); 
},
...

现在,当我在chrome中调试应用程序时,我看到,我永远不会到达_getContentHeight()。现在我很确定它必须与异步调用等做一些事情。但是有没有办法调试它,看看我得到的高度和content_height值是什么?

需要帮助,尤其是在理解 setTimeout/异步函数调用方面。

我建议将调用移动到componentDidMount内部的measure以确保您的功能在抽象它并处理您现在可能面临的任何范围或对象引用问题之前正常工作。

componentDidMount() {
    this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
      // Sets content height in state
      this.setState({
        height: this.props.expanded ? height : 0,
        content_height: height
      });
    });
}

更新:

我已经将您的代码包装在一个反应类中,并让度量对象出错@ https://jsfiddle.net/x7w62w99/

var Hello = React.createClass({
  _getContentHeight() {
            console.log(this.refs)
      if (this.refs.AccordionContent) {
          this.refs.AccordionContent.measure((ox, oy, width, height, px, py) => {
              // Sets content height in state
              this.setState({
                  height: this.props.expanded ? height : 0,
                  content_height: height
              });
          });
      }
  },
  componentDidMount() {
      setTimeout(this._getContentHeight);
  },
  render: function() {
    return <div ref='AccordionContent'>
        Hello {this.props.name}
      <div id='AccordionContent'>
      some stuff
      </div>
    </div>;
  }
});
ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

试试这个

setTimeout(function(){
     this._getContentHeight.bind(this)
})

使用这个:

setTimeout({
   this._getContentHeight
}, the delay you want);

SetTimeout 采用两个参数。http://www.w3schools.com/jsref/met_win_settimeout.asp