开发者问题收集

接收 TypeError:未定义不是一个函数(靠近'...posts.map...')React-Native / Rails 6.0 API

2020-03-02
2140

我试图在 iPhone/Android 设备上运行我的 Expo 应用,但收到了

"undefined is not a function (near'...posts.map...')"

但该应用程序在 iOS 模拟器上运行...它确实在 Android 模拟器上显示错误。我对 React Native 还不太熟悉,我试图弄清楚 为什么它没有返回我的 iPhone(物理)和 Android 模拟器的对象

完整错误如下,我编写的代码将遵循它。 如何修复此 TypeError 问题并在我的 iPhone/Android 模拟器上正确显示结果?

完整错误:

TypeError: undefined is not a function
(near'...posts.map')

    This error is located at:
     in Home (created by
     Context.Consumer)
     in Route (at App.js:21)
     in Switch (at App.js.30)
     in RCTSafeAreaView (at SafeAreaView.js:55)
     in SafeAreaView (at App.js:19)
     in App (at App.js:35)
     in Router (created by Memory Router)
    ....

我的 React Native 代码:

import React, {useState, useEffect} from 'react';
import Axios from 'axios'
import {ScrollView} from 'react-native';
import PhotoPost from '../components/PhotoPost';
import ErrorBoundary from 'react-native-error-boundary'

const Home = () => {
 const [posts, setPosts] = useState([]);

 useEffect( () => {
  Axios.get('http://127.0.0.1:3000/image_post/index')
  .then(res => {
    setPosts(res.data)
  }).catch(e => setPosts(e.message))
}, []);

 return (
  <ScrollView>
    <ErrorBoundary>
      {posts.map((posts, index) => {
        return(
          <PhotoPost key={index} post={post} />
        )
      })}
    </ErrorBoundary>
  </ScrollView>
 )
}

export default Home
2个回答

由于您在 PhotoPost 组件中使用了变量 post,因此您应该使用 (post, index) 而不是 (posts, index)。

<ErrorBoundary>
  {posts.map((post, index) => {
    return(
      <PhotoPost key={index} post={post} />
    )
  })}
</ErrorBoundary>
joyqul
2020-03-02

为了在 JS 中使用 map ,数据必须是一个数组。

catch 中,您直接将错误消息分配给 posts ,作为 setPosts(e.message) 并尝试使用 map。这就是为什么 undefined is not a function (near'...posts.map...') 发生的原因,因为那时 posts 不是数组。

有多种方法可以修复此错误,但最好保留一个单独的状态来处理错误,如下所示,

import React, { useState, useEffect } from "react";
import Axios from "axios";
import { View, Text, ScrollView } from "react-native";
import PhotoPost from "../components/PhotoPost";

const Home = () => {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState(false);

  useEffect(() => {
    Axios.get("http://127.0.0.1:3000/image_post/index")
      .then(res => {
        setPosts(res.data);
      })
      .catch(e => {
        setError(true);
        // log error
        console.log(e);
      });
  }, []);

  return (
    <ScrollView>
      {error ? (
        <View>
          <Text>Error while loading data 😢</Text>
        </View>
      ) : (
        posts.map((post, index) => {
          return <PhotoPost key={index} post={post} />;
        })
      )}
    </ScrollView>
  );
};

export default Home;

希望这对您有所帮助。如有疑问,请随意。

SDushan
2020-03-02