2016-07-28 28 views
0

我想弄清楚如何设置一个反应状态到数据库的值。我正在使用Dexie.js与Dexie.js一起使用Reactjs?

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从我的数据库中获取数据?

回答

2

该问题与Dexie.js(很好的indexDB封装btw)无关。您从作为处理程序传递给.then的回调调用this.setState()。在承诺上下文内调用回调this时为undefined

为了解决这个,你需要明确设置回调的this,使用.bind还是老that = this,或者只是使用箭头功能(demo):

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