【问题标题】:Using Reactjs with Dexie.js?将 Reactjs 与 Dexie.js 一起使用?
【发布时间】:2016-12-03 08:10:38
【问题描述】:

我试图弄清楚如何将反应状态设置为数据库的值。我正在使用Dexie.js

var Duck = React.createClass({
getInitialState:function(){
return { century:'' }
},

fridge:function(){

var db = new Dexie('homie');
db.version(1).stores({
friends:'name, race'});

db.open().catch(function(){
alert("Open failed: ");
});

db.friends.put({name: 'Johnny', race:'hispanic'}).then(function(){
return db.friends.get('Johnny');
}).then(function(samba){
console.log(samba.race);
this.setState({century: samba.race});
});
},

render:function(){
return (<div>
<input type="submit" value="Submeet" onClick={this.fridge} />
<p>{this.state.century}</p>
</div>);
}

fridge 函数有效,因为它将适当的项目放置在数据库中。代码中唯一不起作用的部分是this.setState({century:samba.race})。这会导致Cannot read property 'setState' of undefined 的错误。

我将如何重新执行setState 以从我的数据库中获取数据?

【问题讨论】:

    标签: javascript reactjs dexie


    【解决方案1】:

    这个问题与 Dexie.js 无关(顺便说一句,不错的 indexDB 包装器)。您从作为处理程序传递给.then 的回调中调用this.setState()。当在 promise 上下文中调用回调时,thisundefined

    要解决你需要显式设置回调的this,使用.bind或旧的that = this,或者只使用箭头函数(demo):

     .then((samba) => {
        console.log(samba.race);
        this.setState({
          century: samba.race
        });
      }); 
    

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 2015-03-13
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2018-06-03
      • 2022-07-23
      • 2018-04-08
      相关资源
      最近更新 更多