无法将上下文值绑定到setInterval函数Reactjs

时间:2017-06-01 14:28:08

标签: javascript reactjs

我不得不说,我在几小时内寻找答案而没有任何帮助,所以我的问题在这里:

componentDidMount() {
  var self = this
  console.log(`INIT keys ${this.props.variants}`); // INIT KEYS [Object], [Object] ...
  this.interval = setInterval(function() {
    console.log(`Keys ${self.props.variants}`); // Keys ...
  }.bind(self), 1000)
}

存在初始密钥,但区间内的密钥不存在。
有人能帮我吗? :)

1 个答案:

答案 0 :(得分:0)

this界限中,您必须使用self而不是this。此外,您无需重新声明componentDidMount() { console.log(`INIT keys ${this.props.variants}`); this.interval = setInterval(function() { console.log(`Keys ${this.props.variants}`); }.bind(this), 1000) }

this

如果您可以使用箭头功能,则可以忽略绑定,因为箭头功能不会重新声明componentDidMount() { console.log(`INIT keys ${this.props.variants}`); this.interval = setInterval(() => { console.log(`Keys ${this.props.variants}`); }, 1000) }

let textField = searchBar.value(forKey: "searchField") as! UITextField

let glassIconView = textField.leftView as! UIImageView
glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate)
glassIconView.tintColor = .white


let clearButton = textField.value(forKey: "clearButton") as! UIButton
clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
clearButton.tintColor = .white