[英]Why is the following _.map function returning nothing?
我創建了一個函數來查找對象:
store.js
store.find = () => {
const query = new Parse.Query(Document)
return query.find()
}
我正在這樣使用(並將值分配給this.documents
):
main.js
store.find().then((results) => {
this.documents = _.map(results, (result) => {
return result.toJSON()
})
})
有用。 但是store.find().then( ...)
部分在main.js
重復了很多次,所以我將其變成了一個函數:
store.js
store.fetch = (documents) => {
return store.find().then((results) => {
documents = _.map(results, (result) => {
return result.toJSON()
})
})
}
我這樣使用:
main.js
store.fetch(this.documents)
但是沒有任何內容分配給this.documents
,並且沒有錯誤消息。 可能是什么問題?
注意: this.documents
是一個對象數組。 例:
[{
title: this.title,
content: this.content,
}, ...
編輯:
我這樣做:
store.fetch = (documents) => {
store.find().then((results) => {
documents = _.map(results, (result) => {
return result.toJSON()
})
console.log(documents)
})
}
和documents
被分配:
[Object, Object, Object, ...]
因此,我認為這只是沒有將此數組分配給this.documents
。 也許變量不能是參數,而不能同時賦值?
您正在傳遞this.documents
作為參數,並試圖在函數內部修改該屬性。 但是,這不起作用,因為Javascript沒有“按引用傳遞”功能 。 僅“按值傳遞”。
相反,您可以嘗試分別傳遞對象和屬性名稱:
store.fetch = (obj, prop) => {
return store.find().then((results) => {
obj[prop] = _.map(results, (result) => {
return result.toJSON()
})
})
}
store.fetch(this, 'documents')
嘗試讓你產生一個.then
經過塊store.fetch(this.documents)
並且不要忘記存儲上下文
var self = this;
store.fetch(self.documents).then(function () {
console.log(self.documents);
});
還是usign es6
store.fetch(this.documents).then(() => {
console.log(this.documents);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.