2

反応状態をデータベースの値に設定する方法を見つけようとしています。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データベースからデータを取り込むにはどうすればよいですか?

4

1 に答える 1

3

この問題は Dexie.js とは関係ありません (すばらしい indexDB ラッパーです)。ハンドラーとしてthis.setState()渡すコールバックから呼び出します。.thenpromise コンテキスト内でコールバックが呼び出されるthisと、 undefined.

これを解決するには、 またはoldthisを使用してコールバックのを明示的に設定するか、単にアロー関数 ( demo )を使用する必要があります。.bindthat = this

 .then((samba) => {
    console.log(samba.race);
    this.setState({
      century: samba.race
    });
  }); 
于 2016-07-28T20:06:59.090 に答える