Как подключится к API???

Доброго времени суток!

Я создаю Android-приложение на React Native, пытаюсь получить список, но выдаются ошибки и краши:
TypeError: data.map is not a function. (In 'data.map(function (item) {
          return console.log(item);
        })', 'data.map' is undefined)
* App.js:40:20 in render
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11581:21 in finishClassComponent
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11509:4 in updateClassComponent
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:17276:21 in performUnitOfWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:17316:41 in workLoop
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:17417:15 in renderRoot
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18423:17 in performWorkOnRoot
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18324:24 in performWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18285:14 in performSyncWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18169:19 in requestWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:17969:16 in scheduleWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:6934:17 in enqueueSetState
- node_modules\react\cjs\react.development.js:335:31 in setState
* App.js:22:22 in <unknown>
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in <unknown>
- ... 8 more stack frames from framework internals

Finished building JavaScript bundle in 35ms.

Warning: %s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI., RootErrorBoundary
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:26:24 in error
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:638:36 in warningWithoutStack
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:15918:16 in callback
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:13857:16 in callCallback
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:13901:19 in commitUpdateEffects
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:13892:22 in commitUpdateQueue
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:15123:10 in commitLifeCycles
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:16636:8 in commitAllLifeCycles
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:93:15 in invokeGuardedCallbackImpl
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:318:36 in invokeGuardedCallback
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:16876:8 in commitRoot
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18501:17 in <unknown>
- node_modules\scheduler\cjs\scheduler.development.js:255:23 in unstable_runWithPriority
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18499:4 in completeRoot
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18427:21 in performWorkOnRoot
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18324:24 in performWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18285:14 in performSyncWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:18169:19 in requestWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:17969:16 in scheduleWork
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:6934:17 in enqueueSetState
- node_modules\react\cjs\react.development.js:335:31 in setState
* App.js:22:22 in <unknown>
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in <unknown>
- ... 8 more stack frames from framework internals


Вот сам код:
import React from 'react'
import { StyleSheet, View, ScrollView } from 'react-native'
import { Header, Postcard } from './src/components/uikit'

const app_id = 'A0fYneIZtTWAXAWb4NaKE6xxfpV6sqpozdravkacom'
const category = 'photo_all'

const domain = 'https://admin-pozdravka.herokuapp.com'

export default class App extends React.Component {
    state = {
      title: 'Главная',
      data: []
    }

  componentDidMount = () => {
    try {
      const url = domain + '?app_id='+ app_id +'&category='+ category +'&page=' + this.state.page
      return fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({ data: responseJson })
      })
      .catch((error) =>{
        console.error(error);
      });
    } catch (e) {
      throw e
    }
  }

  render() {
    const { container, postcards } = styles
    const { title, data } = this.state
    return (
      <View style={container}>
        <Header title={title} />
        <ScrollView>
          <View style={postcards}>
          {data.map(item => (
            console.log(item)
          ))}
          </View>
        </ScrollView>
      </View>
    )
   }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  postcards: {
    flex: 12,
    width: '100%'
  }
})


Как исправить??
  • Вопрос задан
  • 536 просмотров
Решения вопроса 2
RomReed
@RomReed
JavaScript, React js, ReactNative, Redux, Firebase
{data&&data.map(item => (
            console.log(item)
          ))}
Ответ написан
@i1yas
У вас из API приходит не массив, а объект. Затем вы записываете его в state и пытаетесь вызвать у объекта .map, которого у него нет.
Смотрите что вам приходит из API и вставляйте в data, что нужно. Скорее всего вы хотели вытащить responseJson.photos
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы