我已经知道什么绑定这样做,这势必给你的对象或功能,你想要的功能,但bind(this)
确实是令人困惑me.What做this
的bind
真正含义。
下面是我的应用程序与firebase数据库的代码。
componentWillMount: function() {
this.firebaseRef = firebase.database().ref('todos');
this.firebaseRef.limitToLast(25).on('value', function(dataSnapshot) {
var items = [];
dataSnapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item['key'] = childSnapshot.key;
items.push(item);
}.bind(this));
this.setState({
todos: items
});
}.bind(this));
},
bind(this)
这里将您函数的上下文绑定forEach()
到componentWillMount()的范围内。
this
这里指的范围componentWillMount()
。
使用bind(this)
,this
内部函数内部的关键字将引用外部范围。这是必不可少的,因为在这种情况下this.setState
,forEach
可以在函数内部调用它,因为它的作用域限于componentWillMount()
。
根据文档:
bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。
查看此演示,演示了的用法bind(this)
。
class App extends React.Component {
constructor(){
super();
this.state = {
data: [{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
}
}
componentDidMount() {
this.state.data.forEach(function(item) {
console.log('outer scope ', this);
}.bind(this))
this.state.data.forEach(function(item) {
console.log('Inner scope ', this);
})
}
render() {
return (
<div>Hello</div>)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句