小编典典

绑定(这)是什么意思?

reactjs

我已经知道什么绑定这样做,这势必给你的对象或功能,你想要的功能,但bind(this)确实是令人困惑me.What做thisbind真正含义。

以下是我的应用程序与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));

  },

阅读 305

收藏
2020-07-22

共1个答案

小编典典

bind(this)这里将您函数的上下文绑定forEach()到componentWillMount()的范围内。

this这里指的是范围componentWillMount()

使用bind(this)this内部函数内部的关键字将引用外部范围。这是必不可少的,因为在这种情况下,
this.setState内部forEach函数可以调用,因为它的作用域限于componentWillMount()

根据
文档

bind()方法创建一个新函数,该函数在被调用时将其this关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

查看此演示,演示了的用法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>
2020-07-22