函数未在 setTimeout 中执行
Function is not being executed within setTimeout
我正在尝试将以下代码与 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
相关文章:
- setTimeout函数能否在其前面的代码执行之前激发
- 在setTimeout完成后执行
- 为什么 setTimeout(., 0) 不立即执行
- 函数未在 setTimeout 中执行
- JavaScript setTimeout() 不会等待执行
- 当超出范围时,延迟执行脚本Jquery(或SetTimeOut)BUT
- eval和setTimeout之间的差异执行字符串代码
- toString似乎导致setTimeout不总是为toString的变量参数执行函数
- 在setTimeout中执行jQuery成员函数而不关闭的方法
- 只有setTimeout执行函数.JS
- setTimeout在IE中执行得很快
- setTimeout()/setInterval()赢得't执行**我正在传递函数对象,而不是执行函数
- nodejs:setImmediate 回调在 setTimeout(fn, 0) 之后执行,与 nodejs 文档描述
- setTimeout 是使用 javascript 执行异步函数的好解决方案吗?
- 我尝试在 1 秒后调用 .hide()(使用 setTimeout),但它是直接执行的,为什么
- 为什么不执行嵌套 setTimeout 中的 removeAttribute 调用
- 如果条件更改,请不要执行 setTimeout
- 在进入下一个循环迭代之前执行setTImeout操作
- 过早执行setTimeout
- 不断执行setTimeout后的setInterval