Компонент Flatlist React-Native предотвращает заполнение моего массива, вызывая сбой приложения - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь загрузить несколько элементов на экране из бэкэнда:

async function loadIncidents() {
    try {
      const response = await api.get("incidents");
      const theData = response.data;
      console.log(theData);
      setIncidents(theData);
      console.log(incidents);
    } catch (e) {
      console.error(e.message);
    }
  }

  useEffect(() => {
    loadIncidents();
  }, []);

Это работает, и я могу видеть свои данные в журнале, но только когда Flatlist, отвечающий за рендеринг каждого item, не комментируется, он не заполняет мой массив и выдает ошибку:

Недопустимая попытка распространения не повторяемого экземпляра. Для того, чтобы быть итеративным, объекты, не являющиеся массивами, должны иметь метод Symbol.iterator. - node_modules@babel \ runtime \ helpers \ nonIterableSpread. js: 2: 22 в _nonIterableSpread - node_modules@babel \ runtime \ helpers \ toConsumableArray. js: 10: 111 в _toConsumableArray * src \ pages \ Incidents \ index. js: 54: 6 в Инцидентах - node_modules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 10696: 27 в renderWithHooks - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev . js: 12842: 6 в updateFunctionComponent - node_modules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 307: 15 в invokeGuardedCallbackImpl - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRativeNativeRative -dev. js: 531: 36 в invokeGuardedCallback - node_modules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 20488: 8 в beginWork $$ 1 - node_modules \ реагировать-родной \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 19370: 24 в executeUnitOfWork - node_modules \ react-native \ Libraries \ Rend erer \ Implementations \ ReactNativeRenderer-dev. js: 19347: 39 в workLoopSync - node_modules \ реагировать-нативный \ Библиотеки \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 18997: 22 в renderRoot * [собственный код]: пусто в renderRoot - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 18709: 28 в runRootCallback * [собственный код]: пусто в runRootCallback - node_modules \ реагировать-родной \ Libraries \ Renderer \ Implementations \ \ ReactNativeRenderer-dev. js: 5642: 32 в runWithPriority $ arguments_1 - node_modules \ scheduler \ cjs \ scheduler.development. js: 643: 23 в unstable_runWithPriority - node_modules \ реагировать-в родном виде \ Libraries \ Renderer \-reativeRenations_ реализации dev. js: 5638: 22 в flushSyncCallbackQueueImpl - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 5627: 28 в flushSyncCallbackQueue - node_modules \ реагировать-native \ Libraries \ Renderer ReactNativeRenderer-dev. js: 18556: 30 в расписанииОбновитьОнффи ber - node_modules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 11484: 17 в dispatchAction * [собственный код]: пусто в dispatchAction * src \ pages \ Incidents \ index. js: 29 : 18 в loadIncidents - node_modules \ регенератор-время выполнения \ runtime. js: 45: 44 в tryCatch - node_modules \ регенератор-время выполнения \ runtime. js: 274: 30 в invoke - node_modules \ регенератор-время выполнения \ runtime. js: 45: 44 в tryCatch - node_modules \ регенератор-время выполнения \ runtime. js: 135: 28 в invoke - node_modules \ регенератор-время выполнения \ runtime. js: 145: 19 в PromiseImpl.resolve.then $ аргумент_0 - node_modules \ обещание \ setimmediate \ core. js: 37: 14 в tryCallOne - node_modules \ обещание \ setimmediate \ core. js: 123: 25 в setImmediate $ arguments_0
- node_modules \ реагировать-родной \ Libraries \ Core \ Timers \ JSTimers. js: 146: 14 в _callTimer - узлы_модулей \act-native \ Библиотеки \ Core \ Timers \ JSTimers. js: 194: 17 в _callImmediatesPass - узлы_модулей \ реагировать-native \ Libraries \ Core \ Таймеры \ JSTimers js:. 458: 30 в callImmediates * [собственный код]: null в callImmediates - node_modules \ реагировать-нативный \ Libraries \ BatchedBridge \ MessageQueue. js: 407: 6 в __callImmediates - ноды-модули \ реагировать-родной \ Libraries \ BatchedBridge \ MessageQueue. js: 143: 6 в __guard $ аргумент_0 - узлы_модулей \ реагировать-нативный \ Библиотеки \ BatchedBridge \ MessageQueue. js: 384: 10 в __guard - нод_модули \ реагировать-нативный \ Библиотеки \ BatchedBridge \ MessageQueue. js: 142: 17 в __guard $ argument_0 * [собственный код]: ноль в flhedQueue * [собственный код]: ноль в callFunctionReturnFlushedQueue

Предупреждение:% s: границы ошибок должны реализовывать getDerivedStateFromError (). В этом методе возвращают обновление состояния для отображения сообщения об ошибке или резервного интерфейса. RootErrorBoundary - node_modules \ реагировать-native \ Libraries \ YellowBox \ YellowBox. js: 63: 8 в console.error - node_modules \ expo \ build \ environment \ muteWarnings.fx. js: 27: 24 по ошибке - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 645: 36 в предупрежденииWithoutStack - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 18056: 16 в обратном вызове - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 7595: 16 в callCallback - node_modules \ реагировать-собственный \ Библиотеки \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 7639: 19 в commitUpdateEffects - node_modules \ response-native \ Библиотеки \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 7630: 22 в commitUpdateQueue - node_modules native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 17116: 10 в commitLifeCycles - node_m odules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 20002: 23 в commitLayoutEffects - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 307: 15 в invokeGuardedCallbackImpl - node_modules \ react-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 531: 36 в invokeGuardedCallback - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. *: 6862: 1062 10 в commitRootImpl * [собственный код]: null в commitRootImpl - node_modules \ scheduler \ cjs \ scheduler.development. js: 643: 23 в unstable_runWithPriority - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRende. 1064 *: 19590: 4 в commitRoot * [собственный код]: null в commitRoot - node_modules \ реагировать-native \ Libraries \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 18709: 28 в runRootCallback * [собственный код]: null в runRootCallback - node_modules \ реагировать-родной \ Libraries \ Renderer \ Implementatio ns \ ReactNativeRenderer-dev. js: 5642: 32 в runWithPriority $ arguments_1 - node_modules \ scheduler \ cjs \ scheduler.development. js: 643: 23 в unstable_runWithPriority - node_modules \ реагировать-в родном виде \ Libraries \ Renmenrer \ Renderer ReactNativeRenderer-dev. js: 5638: 22 в flushSyncCallbackQueueImpl - node_modules \act-native \ Библиотеки \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 5627: 28 в flushSyncCallbackQue - node_modules \ реагировать-реактивные реализации \ ReactNativeRenderer-dev. js: 18556: 30 в scheduleUpdateOnFiber - node_modules \ реагировать-нативный \ Библиотеки \ Renderer \ Implementations \ ReactNativeRenderer-dev. js: 11484: 17 в диспетчерской операции * [собственный код]: ноль в диспетчерской операции * src \ pages \ Incidents \ index. js: 29: 18 в loadIncidents - node_modules \ регенератор-runtime \ runtime. js: 45: 44 в tryCatch - node_modules \ регенератор-runtime \ runtime. js: 274 : 30 в вызове - node_modules \ регенератор-время выполнения \ время выполнения. js: 45: 44 в tryCatch - нод_модули \ регенератор -runtime \ runtime. js: 135: 28 in invoke - node_modules \ регенератор-runtime \ runtime. js: 145: 19 в PromiseImpl.resolve.then $ arguments_0 - node_modules \ обещание \ setimmediate \ core. js : 37: 14 в tryCallOne - node_modules \ обещать \ setimmediate \ core. js: 123: 25 в setImmediate $ arguments_0
- node_modules \ реагировать-родной \ Libraries \ Core \ Timers \ JSTimers. js: 146: 14 в _callTimer - узлы_модулей \ реагировать-нативный \ Библиотеки \ Core \ Timers \ JSTimers. js: 194: 17 в _callImmediatesPass - ноды-модулей \ реагировать-нативный \ Библиотеки \ Core \ Timers \ JSTimers. js: 458: 30 в callImmediates * [собственный код]: ноль в callImmediates - node_modules \ реагировать-нативный \ Libraries \ BatchedBridge \ MessageQueue. js: 407: 6 в __callImmediates - node_modules \ react-native \ Libraries \ BatchedBridge \ MessageQueue. js: 143: 6 в __guard $ arguments_0 - node_modules \ реагировать-native \ Libraries \ BatchedBridge \ MessageQueue. js: 384: 10 в __guard r - узлы_модулей \ реагировать-нативный \ Библиотеки \ Core \ Timers \ JSTimers. js: 194: 17 в _callImmediatesPass - узлы_модулей \ реагировать-нативный \ Библиотеки \ Core \ Timers \ JSTimers. js: 458: 30 в callImmediates * [родной code]: null в callImmediates - node_modules \ react-native \ Libraries \ BatchedBridge \ MessageQueue. js: 407: 6 в __callImmediates - node_modules \ реагировать-native \ Libraries \ BatchedBridge \ MessageQueue. js: 143: 6 в __guard $ аргумент_0 - узлы_модулей \ реагировать-нативный \ Библиотеки \ BatchedBridge \ MessageQueue. js: 384: 10 в __guard - модули_узлов \ реагировать-нативный \ Библиотеки \ BatchedBridge \ MessageQueue. js: 142: 17 в __guard $ аргумент_0 * [ собственный код]: ноль в flhedQueue * [собственный код]: ноль в callFunctionReturnFlushedQueue

Похоже, что Flatlist препятствует моей функции loadIncid ents () заполняет мой массив, когда Flatlist присутствует и вызывает мою переменную, массив возвращает пустой. Я попытался несколько способов отладки, но не сработает. Вот плоский список, ничего особенного:

<FlatList
     data={incidents}
     style={styles.incidentList}
     keyExtractor={(incident) => String(incident.id)}
     showsVerticalScrollIndicator={false}
     renderItem={({ item: incident }) => (
       <View style={styles.incident}>
         <Text style={styles.incidentProperty}>NGO:</Text>
         <Text style={styles.incidentValue}>{incident.name}</Text>
       </View>
     )}
 />

Ответы [ 3 ]

0 голосов
/ 17 апреля 2020

Данные, возвращаемые из вызова API

> Object {   "config": Object {
>     "adapter": [Function xhrAdapter],     
>     "baseURL": "http://192.168.xxx.xxx:3333",
>     "data": undefined,
>     "headers": Object {
>       "Accept": "application/json, text/plain, */*",
>     },
>     "maxContentLength": -1,
>     "method": "get",
>     "params": Object {
>       "page": 1,
>     },
>     "timeout": 0,
>     "transformRequest": Array [
>       [Function transformRequest],
>     ],
>     "transformResponse": Array [
>       [Function transformResponse],
>     ],
>     "url": "/incidents",
>     "validateStatus": [Function validateStatus],
>     "xsrfCookieName": "XSRF-TOKEN",
>     "xsrfHeaderName": "X-XSRF-TOKEN",   },   "data": Object {
>     "incidents": Array [
>       Object {
>         "city": "Vancouver",
>         "description": "details of the Incident report",
>         "email": "info@apade.ca",
>         "id": 3,
>         "name": "Apade",
>         "ngo_id": "5209f9ae",
>         "state": "BC",
>         "title": "IR 2",
>         "value": 110,
>         "whatsapp": "604 123 1234",
>       },
>       Object {
>         "city": "Vancouver",
>         "description": "details of the Incident report",
>         "email": "info@apade.ca",
>         "id": 6,
>         "name": "Apade",
>         "ngo_id": "5209f9ae",
>         "state": "BC",
>         "title": "IR 4",
>         "value": 120,
>         "whatsapp": "604 123 1234",
>       },
>       Object {
>         "city": "Vancouver",
>         "description": "details of the Incident report",
>         "email": "info@apade.ca",
>         "id": 7,
>         "name": "Apade",
>         "ngo_id": "5209f9ae",
>         "state": "BC",
>         "title": "IR 5",
>         "value": 120,
>         "whatsapp": "604 123 1234",
>       },
>       Object {
>         "city": "Vancouver",
>         "description": "details of the Incident report",
>         "email": "info@apade.ca",
>         "id": 8,
>         "name": "Apade",
>         "ngo_id": "5209f9ae",
>         "state": "BC",
>         "title": "IR 6",
>         "value": 120,
>         "whatsapp": "604 123 1234",
>       },
>       Object {
>         "city": "Vancouver",
>         "description": "details of the Incident report",
>         "email": "info@apade.ca",
>         "id": 9,
>         "name": "Apade",
>         "ngo_id": "5209f9ae",
>         "state": "BC",
>         "title": "IR 7",
>         "value": 120,
>         "whatsapp": "604 123 1234",
>       },
>     ],   },   "headers": Object {
>     "access-control-allow-origin": "*",
>     "cache-control": "public, max-age=0",
>     "connection": "keep-alive",
>     "content-length": "1015",
>     "content-type": "application/json; charset=utf-8",
>     "date": "Fri, 17 Apr 2020 17:18:17 GMT",
>     "etag": "W/\"3f7-qB7SdnrSk8xOqSo8f9RGhorMNdk\"",
>     "x-powered-by": "Express",
>     "x-total-count": "12",   },   "request": XMLHttpRequest {
>     "DONE": 4,
>     "HEADERS_RECEIVED": 2,
>     "LOADING": 3,
>     "OPENED": 1,
>     "UNSENT": 0,
>     "_aborted": false,
>     "_cachedResponse": undefined,
>     "_hasError": false,
>     "_headers": Object {
>       "accept": "application/json, text/plain, */*",
>     },
>     "_incrementalEvents": false,
>     "_lowerCaseResponseHeaders": Object {
>       "access-control-allow-origin": "*",
>       "cache-control": "public, max-age=0",
>       "connection": "keep-alive",
>       "content-length": "1015",
>       "content-type": "application/json; charset=utf-8",
>       "date": "Fri, 17 Apr 2020 17:18:17 GMT",
>       "etag": "W/\"3f7-qB7SdnrSk8xOqSo8f9RGhorMNdk\"",
>       "x-powered-by": "Express",
>       "x-total-count": "12",
>     },
>     "_method": "GET",
>     "_requestId": null,
>     "_response": "{\"incidents\":[{\"id\":3,\"title\":\"IR 2\",\"description\":\"details of the Incident
> report\",\"value\":110,\"ngo_id\":\"5209f9ae\",\"name\":\"Apade\",\"email\":\"info@apade.ca\",\"whatsapp\":\"604
> 123
> 1234\",\"city\":\"Vancouver\",\"state\":\"BC\"},{\"id\":6,\"title\":\"IR
> 4\",\"description\":\"details of the Incident
> report\",\"value\":120,\"ngo_id\":\"5209f9ae\",\"name\":\"Apade\",\"email\":\"info@apade.ca\",\"whatsapp\":\"604
> 123
> 1234\",\"city\":\"Vancouver\",\"state\":\"BC\"},{\"id\":7,\"title\":\"IR
> 5\",\"description\":\"details of the Incident
> report\",\"value\":120,\"ngo_id\":\"5209f9ae\",\"name\":\"Apade\",\"email\":\"info@apade.ca\",\"whatsapp\":\"604
> 123
> 1234\",\"city\":\"Vancouver\",\"state\":\"BC\"},{\"id\":8,\"title\":\"IR
> 6\",\"description\":\"details of the Incident
> report\",\"value\":120,\"ngo_id\":\"5209f9ae\",\"name\":\"Apade\",\"email\":\"info@apade.ca\",\"whatsapp\":\"604
> 123
> 1234\",\"city\":\"Vancouver\",\"state\":\"BC\"},{\"id\":9,\"title\":\"IR
> 7\",\"description\":\"details of the Incident
> report\",\"value\":120,\"ngo_id\":\"5209f9ae\",\"name\":\"Apade\",\"email\":\"info@apade.ca\",\"whatsapp\":\"604
> 123 1234\",\"city\":\"Vancouver\",\"state\":\"BC\"}]}",
>     "_responseType": "",
>     "_sent": true,
>     "_subscriptions": Array [],
>     "_timedOut": false,
>     "_trackingName": "unknown",
>     "_url": "http://192.168.xxx.xxx:3333/incidents?page=1",
>     "readyState": 4,
>     "responseHeaders": Object {
>       "Access-Control-Allow-Origin": "*",
>       "Cache-Control": "public, max-age=0",
>       "Connection": "keep-alive",
>       "Content-Length": "1015",
>       "Content-Type": "application/json; charset=utf-8",
>       "Date": "Fri, 17 Apr 2020 17:18:17 GMT",
>       "ETag": "W/\"3f7-qB7SdnrSk8xOqSo8f9RGhorMNdk\"",
>       "X-Powered-By": "Express",
>       "X-Total-Count": "12",
>     },
>     "responseURL": "http://192.168.xxx.xxx:3333/incidents?page=1",
>     "status": 200,
>     "timeout": 0,
>     "upload": XMLHttpRequestEventTarget {},
>     "withCredentials": true,   },   "status": 200,   "statusText": undefined, }
0 голосов
/ 17 апреля 2020

FlatList должен получать массивы как данные, ошибка, которую вы получаете, это то, что вы вместо этого дали объект Object, так как вы отправили сообщение, полученное из ответа API.

Похоже, вам нужно


 setIncidents(theData.incidents)

Вместо.

Еще одна вещь об этом


  setIncidents(theData);
  console.log(incidents)

В общем,

SetState является асин c вызовите, поэтому регистрируемая переменная в любом случае будет предыдущей здесь

0 голосов
/ 17 апреля 2020

Вы можете отправить код всего компонента и структуру данных об инцидентах? В сообщении говорится, что вы пытаетесь распространить не повторяемый экземпляр. Может быть, вы получаете непарсированный json объект? Если это так, попробуйте использовать JSON .parse для преобразования строки json в js структуру

...