首页 > 解决方案 > NativeScript ListView Error when updating / changing the array it depends on

问题描述

I'm creating a chat app with nativescript where I Can load more messages with a specific method. These newly loaded messages are added to the beginning of the messages-array. Now as soon as the messages array changes from which the listview gets its items, it gives me the error:

ERROR TypeError: Cannot read property 'length' of undefined`

    ERROR CONTEXT {
JS:   "view": {
JS:     "def": {
JS:       "nodeFlags": 38518785,
JS:       "rootNodeFlags": 1,
JS:       "nodeMatchedQueries": 0,
JS:       "flags": 0,
JS:       "nodes": [
JS:         {
JS:           "nodeIndex": 0,
JS:           "parent": null,
JS:           "renderParent": null,
JS:           "bindingIndex": 0,
JS:           "outputIndex": 0,
JS:           "checkIndex": 0,
JS:           "flags": 1,
JS:           "childFlags": 38518785,
JS:           "directChildFlags": 33554433,
JS:           "childMatchedQueries": 0,
JS:           "matchedQueries": {},
JS:           "matchedQueryIds": 0,
JS:           "references": {},
JS:           "ngContentIndex": null,
JS:           "childCount": 2,
JS:           "bindings": [],
JS:           "bindingFlags": 0,
JS:           "outputs": [],
JS:           "element": {
JS:             "ns": "",
JS:             "name": "StackLayout",
JS:             "attrs": [],
JS:             "template": null,
JS:             "componentProvider": null,
JS:             "componentView": null,
JS:             "componentRendererType": null,
JS:             "publicProviders": {},
JS:             "allProviders": "[Ci...

This is my method

this.moreMessagesSub = this.socket.more_messages_receiver$.subscribe(
(messages: Message[]) => {
  this.currentRoom.messages = messages.concat(this.currentRoom.messages); // This leads to the error.
  this.listViewComponent.nativeElement.notifyPullToRefreshFinished();
  this.changeRef.detectChanges();
 }
);

And here I show you my listview.

 <StackLayout row="0" col="0" colSpan="2">
        <RadListView #chatListView pullToRefresh="true" (pullToRefreshInitiated)="onPullToLoadMore()" [items]="currentRoom.messages" separatorColor="white" height="100%">
            <ng-template tkListItemTemplate let-message="item" let-i="index">
                <StackLayout>

                    <ns-chat-message [message]="message" ></ns-chat-message>

                </StackLayout>
            </ng-template>
        </RadListView>
    </StackLayout>

When I remove the line this.currentRoom.messages = messages.concat(this.currentRoom.messages); I am getting no errors. I also tried to use array.unshift here but its exactly the same result. So why does nativescript listview loses the array when it gets renewed? It is obviously just for a really short amount of time. After the Error and some lagging it continues to work like expected and even added the messages in op successfully

标签: javascriptangularlistviewnativescriptangular2-nativescript

解决方案


推荐阅读