函数未在setTimeout中执行

时间:2016-04-23 20:47:20

标签: javascript reactjs react-native

我正在尝试使用以下代码与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 /异步函数调用时。

3 个答案:

答案 0 :(得分:1)

我建议将调用移至measure componentDidMount以确保您的功能在抽象之前有效,并处理您现在可能遇到的任何范围或对象引用问题。< / p>

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
      });
    });
}

更新

我已将您的代码包装在react类中,并使measure对象出错@ 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')
);

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:-2)

使用此:

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

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