我试图弄清楚如何将 react 状态设置为数据库的值。我正在使用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})
。这会导致无法读取未定义的属性“setState”
错误。
如何重新执行 setState
以从数据库中获取数据?
最佳答案
该问题与 Dexie.js(顺便说一句,不错的 indexDB 包装器)无关。您可以从作为处理程序传递给 .then
的回调中调用 this.setState()
。当回调在 Promise 上下文中调用时,this
是 undefined
。
要解决这个问题,您需要使用 .bind
或旧的 that = this
显式设置回调的 this
,或者只是使用箭头函数( demo ):
.then((samba) => {
console.log(samba.race);
this.setState({
century: samba.race
});
});
关于javascript - 将 Reactjs 与 Dexie.js 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644751/