繁体   English   中英

阵列推送无法在React应用程序中按预期方式工作

[英]Array push not working as expected in react app

在我的应用程序做出反应,我使用MobX国有management.After处理Ajax响应我试图push到店。 但是事实证明,它只是无法按预期工作。 这里的代码:

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. 映射不理想,使用forEach遍历元素
2.关联数组是对象{} ,而不是array [] 因此, 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);
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM