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

时间:2018-12-20 13:32:13

标签: javascript reactjs react-native setstate

这是我与本机互动的第一天,我正在与mangodb一起工作,我将记录存储在db中并提取了记录,现在我想在平面列表中显示,并且需要使用setState(),但是会引发未定义的错误

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

docs是一组用户,我可以在控制台中打印数据,它可以正常工作,但是问题是如何使用setState在数据源中设置此数据。

1 个答案:

答案 0 :(得分:5)

这与您调用setState的方式有关。函数上下文中的import 'package:flutter/material.dart'; void main() => runApp(MaterialApp(home: MyApp())); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: DefaultTabController( initialIndex: 0, length: 2, child: Scaffold( body: TabBarView( children: <Widget>[Page1(), Page2()], ), bottomNavigationBar: Material( child: TabBar( labelColor: Colors.black, tabs: <Widget>[ Tab( icon: Icon(Icons.check), ), Tab( icon: Icon(Icons.check), ), ], ), ), ), ), ); } } class Page1 extends StatefulWidget { @override Page1State createState() { return new Page1State(); } } class Page1State extends State<Page1> with AutomaticKeepAliveClientMixin { @override Widget build(BuildContext context) { return ListView( children: <Widget>[ Container( height: 300, color: Colors.orange, ), Container( height: 300, color: Colors.pink, ), Container( height: 300, color: Colors.yellow, child: Center( child: Container(height: 26, child: MaterialButton( color: Colors.blue, child: Text('clicking this and back then swipe => page loses state'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => PushedPage()), ); }), ), ), ), ], ); } @override bool get wantKeepAlive => true; } class Page2 extends StatelessWidget { @override Widget build(BuildContext context) { return Container(height: 300, color: Colors.orange); } } class PushedPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Container( color: Colors.blue, ), ); } } 没有指向组件类。解决它的一种方法是使用箭头功能:

this

如果不能使用箭头功能,则可以手动将功能绑定到外部上下文:

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

此问题中对function cb (err, docs) { this.setState({ dataSource: docs }); } db.find({}, cb.bind(this)); 关键字背后的逻辑进行了详细讨论:How does the "this" keyword work?或在凯尔·辛普森(Kyle Simpson)的这本令人惊叹的书中:YDKJS: this & object prototypes

相关问题