[英]Using Reactjs with Dexie.js?
I am trying to figure out how to set a react state to the value of the database. 我试图弄清楚如何将反应状态设置为数据库的值。 I am using Dexie.js . 我正在使用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>);
}
The fridge
function works, as it places the appropriate item in the database. fridge
功能可以正常运行,因为它会将适当的项目放置在数据库中。 The only part of the code that does not work is this.setState({century:samba.race})
. 代码中唯一无效的部分是this.setState({century:samba.race})
。 This leads to errors of Cannot read property 'setState' of undefined
. 这导致Cannot read property 'setState' of undefined
错误。
How would I re-do the setState
to take in the data from my db? 我将如何重新执行setState
以从数据库中获取数据?
The problem is not related to Dexie.js (nice indexDB wrapper btw). 该问题与Dexie.js(不错的indexDB包装器btw)无关。 You invoke this.setState()
from a callback you pass to .then
as handler. 您从传递给this.setState()
的回调中调用this.setState()
.then
作为处理程序。 When the callback is invoked inside the promise context this
is undefined
. 当在promise上下文中调用回调时, this
是undefined
。
To solve that you need to explicitly set the this
of the callback, using .bind
or the old that = this
, or just use an arrow function ( demo ): 为了解决这个,你需要明确设置this
回调,使用.bind
还是老that = this
,或者只是使用箭头功能( 演示 ):
.then((samba) => {
console.log(samba.race);
this.setState({
century: samba.race
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.