简体   繁体   English

从数据库中获取数据后,setState无法在React Native中工作

[英]setState not working in react native after fetching data from database

It is my first day with react native, I am working with mangodb, I stored record in db and fetched record, now I want to show in flatlist, and need to setState() but it throws error of undefined 这是我与react native的第一天,我正在与mangodb一起工作,我将记录存储在db中并提取了记录,现在我想在平面列表中显示,并且需要setState(),但是会引发未定义的错误

db.find({}, function (err, docs) {
      this.setState({ dataSource: docs });   
});

docs is array of users and I am able to print data in console, its working, but problem is how do I set this data in datasource using setState. docs是一组用户,我可以在控制台中打印数据,它可以正常工作,但是问题是如何使用setState在数据源中设置此数据。

It's related to the way you call setState. 它与您调用setState的方式有关。 this inside the context of your function is not pointing to the component class. 在函数的上下文中, this并不指向组件类。 One way to solve it is to use an arrow function: 解决它的一种方法是使用箭头功能:

db.find({}, (err, docs) => {
      this.setState({ dataSource: docs });   
});

If you can't use arrow functions, you can do the binding of your function to the outside context manually: 如果您不能使用箭头函数,则可以手动将函数绑定到外部上下文:

function cb (err, docs) {
      this.setState({ dataSource: docs });   
}

db.find({}, cb.bind(this));

The logic behind this keyword in javascript is discussed in detail in this question: How does the "this" keyword work? 这个问题将详细讨论javascript中this关键字的逻辑: “ this”关键字如何工作? Or in this amazing book by Kyle Simpson: YDKJS: this & object prototypes 或在Kyle Simpson 撰写的这本惊人的书中: YDKJS:this&object prototypes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM