-1

在我的 React 应用程序中,我使用 MobX 进行状态管理。处理 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);
        });
    }
}
4

1 回答 1

2

根据您当前的代码。
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);
        });
    }
}
于 2017-01-19T11:37:46.467 回答