Javascript 有没有一种方法可以得到;此.lastID“;使用es6和react类从sqlite.run()回调
我想从Javascript 有没有一种方法可以得到;此.lastID“;使用es6和react类从sqlite.run()回调,javascript,node.js,reactjs,sqlite,ecmascript-6,Javascript,Node.js,Reactjs,Sqlite,Ecmascript 6,我想从sqlite.run('insert INTO table…',{},callback)函数的回调内部获取“last insert id”。文档说,可以在回调函数中使用this.lastID 在我的项目中,我将react和node.js(electron)与es6类一起使用。因此,我的回调函数是一个箭头函数(根据mdn的文档),它没有自己的this,而是使用周围代码的this(在本例中是我的react类): 我尝试切换到回调函数的经典声明,结果如下: function(error) {
sqlite.run('insert INTO table…',{},callback)
函数的回调内部获取“last insert id”。文档说,可以在回调函数中使用this.lastID
在我的项目中,我将react和node.js(electron)与es6类一起使用。因此,我的回调函数是一个箭头函数(根据mdn的文档),它没有自己的this
,而是使用周围代码的this
(在本例中是我的react类):
我尝试切换到回调函数的经典声明,结果如下:
function(error) {
...
console.log(this.lastID); // is available
this.props.route.history.push('...'); // cannot access property route of undefined
}
这两种行为都是可以理解的,但是有没有一种方法可以同时从回调函数中获取
this.lastID
和从react类中获取this.props
或this.state
?显然,您不能有两个不同的this
值
最简单的解决方案是在闭包中捕获外部上下文
const component = this
this.db.run(
'INSERT INTO table...',
{},
function (error) {
console.log(this.lastId) // is available
// check error
if(error !== null) {
component.props.addNotification({
open: true,
variant: 'error',
message: error.message,
autoClose: null,
});
} else {
component.props.route.history.push('/...');
component.props.closeForm();
}
}
);
或者您可以创建一个temp normal函数,将this.lastId
作为第二个参数传递给回调函数
this.db.run(
'INSERT INTO table...',
{},
(cb => function(){return cb(error, this.lastId)})((error, lastId) => {
console.log(lastId) // is available
// check error
if(error !== null) {
this.props.addNotification({
open: true,
variant: 'error',
message: error.message,
autoClose: null,
});
} else {
this.props.route.history.push('/...');
this.props.closeForm();
}
})
)
您可以执行以下操作:
// above function
const self= this;
// inside function
function(error) {
this.lastId;
self.props.history;
self.state;
}
var组件=此;//外部作用域
然后component.props.route//内部回调
或进入fancy(cb=>function(error){return cb(error,this.lastId)})((error,lastId)=>{})
我将尝试一下那个“fancy”解决方案,让我这个
成为当前函数体中的react对象这个。。。
// above function
const self= this;
// inside function
function(error) {
this.lastId;
self.props.history;
self.state;
}