javascript - 函数未在 setTimeout 内执行

标签 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/异步函数调用方面。

最佳答案

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

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 ​​类中,并使测量对象出错@ 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')
);

关于javascript - 函数未在 setTimeout 内执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816222/

相关文章:

javascript - navigator.geolocation.getCurrentPosition 超时未触发错误回调

javascript - IE8 中 jQuery.fadeIn 的字体抗锯齿问题?

reactjs - Next.js getServerSideProps 重定向 ERR_HTTP_HEADERS_SENT 错误

javascript - 将输入中的值添加到数组中在 React 中不起作用

css - 如何在 React Native 中使用 flexbox 使一项居中?

react-native - React Navigation v5 setOptions 不起作用

javascript - Ember 计算属性不适用于服务器数据

javascript - 无法读取未定义的属性 'toString', 'isNan'

javascript - 如何将子组件的状态传递给父组件?

react-native - 在 React Native 中使用 WebView 的正确方法是什么