我正在尝试在iPhone / Android设备上运行Expo App,但收到了
“未定义不是函数(在'... posts.map ...'附近)”
但是应用程序在iOS模拟器上运行...它确实在Android模拟器上显示错误。我是React Native的新手,我想弄清楚为什么它不为我的iPhone(物理)和Android Emulator返回对象。
下面是完整的错误,我所写的代码将紧随其后。 如何解决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本机代码:
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
答案 0 :(得分:0)
您应该使用(post,index)而不是(posts,index),因为您在组件PhotoPost中使用了变量post。
<ErrorBoundary>
{posts.map((post, index) => {
return(
<PhotoPost key={index} post={post} />
)
})}
</ErrorBoundary>
答案 1 :(得分:0)
为了在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;
希望这对您有所帮助。放心怀疑。