Javascript 阵列推送在react应用程序中未按预期工作
在我的React应用程序中,我使用MobX进行状态管理。在处理ajax响应后,我尝试Javascript 阵列推送在react应用程序中未按预期工作,javascript,reactjs,mobx-react,Javascript,Reactjs,Mobx React,在我的React应用程序中,我使用MobX进行状态管理。在处理ajax响应后,我尝试推送存储。但事实证明它并没有像预期的那样工作。代码如下: export class Diary { @observable loaded = false; @observable posts = []; @action getPosts() { axios({ method: 'get', url: '/api/diary/
推送存储。但事实证明它并没有像预期的那样工作。代码如下:
export class Diary {
@observable loaded = false;
@observable posts = [];
@action getPosts() {
axios({
method: 'get',
url: '/api/diary/',
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
}).then(action('response action', (response) => {
(response.data).map(function (post) {
let hiren = [];
hiren['id'] = post['id'];
hiren['title'] = Crypt.decrypt(post['title'], key, post['iv']);
hiren['content'] = Crypt.decrypt(post['content'], key, post['iv']);
hiren['tag'] = post['tag'];
hiren['date'] = moment.utc(post['date']).local().format("dddd, DD MMMM YYYY hh:mm:ss A");
this.posts.push.apply(this.posts, hiren);
console.log(toJS(this.posts)); // empty array so the push is not working
}.bind(this));
this.loaded = true;
})).catch(function(err) {
console.error(err);
});
}
}
根据您当前的代码。
1. map不理想,请使用forEach迭代元素
2.关联数组是对象{},而不是数组[]。因此,hiren={}代码>
3.要推入数组,只需直接调用this.posts.push(hiren)代码>针对数组
export class Diary {
@observable loaded = false;
@observable posts = [];
@action getPosts() {
axios({
method: 'get',
url: '/api/diary/',
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
}).then(action('response action', (response) => {
(response.data).forEach(function (post) {
/* Associative array is an OBJECT, NOT AN ARRAY ... */
var hiren = {};
hiren['id'] = post['id'];
hiren['title'] = Crypt.decrypt(post['title'], key, post['iv']);
hiren['content'] = Crypt.decrypt(post['content'], key, post['iv']);
hiren['tag'] = post['tag'];
hiren['date'] = moment.utc(post['date']).local().format("dddd, DD MMMM YYYY hh:mm:ss A");
this.posts.push(hiren);
console.log(toJS(this.posts)); // empty array so the push is not working
});
this.loaded = true;
})).catch(function(err) {
console.error(err);
});
}
}
我想在这里这是不可识别的,因为它在一个函数中,只是在ajax调用之前尝试分配var self=this,而在函数中使用self.posts,而不是这个仍然相同的问题。您已经初始化了hiren
,作为一个数组,但随后继续在其上设置命名属性。它仍然只是一个空数组。您希望posts
在操作后看起来像什么?hiren是一个关联数组,因此它不会将其扩展到push。apply@Phil像这样的{hirenArray1,hirenArray2}