Android 接收类型错误:未定义不是函数(接近';…posts.map…';)React Native/Rails 6.0 API
我试图在iPhone/Android设备上运行我的Expo应用程序,但我收到 “undefined不是函数(靠近“…posts.map…”) 但应用程序在iOS emulator上运行…它在Android emulator上显示错误。我对React Native还比较陌生,我正试图弄明白为什么它不返回iPhone(物理)和Android Emulator的对象 下面是完整的错误,我编写的代码将遵循它如何解决此类型错误问题并在iPhone/Android模拟器上正确显示结果? 完全错误:Android 接收类型错误:未定义不是函数(接近';…posts.map…';)React Native/Rails 6.0 API,android,ruby-on-rails,reactjs,react-native,Android,Ruby On Rails,Reactjs,React Native,我试图在iPhone/Android设备上运行我的Expo应用程序,但我收到 “undefined不是函数(靠近“…posts.map…”) 但应用程序在iOS emulator上运行…它在Android emulator上显示错误。我对React Native还比较陌生,我正试图弄明白为什么它不返回iPhone(物理)和Android Emulator的对象 下面是完整的错误,我编写的代码将遵循它如何解决此类型错误问题并在iPhone/Android模拟器上正确显示结果? 完全错误: Type
TypeError:未定义不是函数
(靠近“…posts.map”)
此错误位于:
在家中(由创建)
(消费者)
途中(在App.js:21)
in Switch(在App.js.30中)
在RCTSafeAreaView中(在SafeAreaView.js:55中)
在SafeAreaView中(位于App.js:19)
应用程序内(位于App.js:35)
路由器内(由内存路由器创建)
....
我的本地代码:
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
import React,{useState,useffect}来自“React”;
从“Axios”导入Axios
从“react native”导入{ScrollView};
从“../components/PhotoPost”导入PhotoPost;
从“反应本机错误边界”导入ErrorBoundary
常量Home=()=>{
const[posts,setPosts]=useState([]);
useffect(()=>{
Axios.get()http://127.0.0.1:3000/image_post/index')
。然后(res=>{
设置柱(res.data)
}).catch(e=>setPosts(e.message))
}, []);
返回(
{posts.map((posts,index)=>{
返回(
)
})}
)
}
导出默认主页
您应该使用(post,索引)而不是(post,索引),因为您在组件PhotoPost中使用变量post
{posts.map((post,index)=>{
返回(
)
})}
要在JS中使用map
,数据必须是数组
在catch
中,您直接将错误消息分配给posts
作为setPosts(e.message)
&尝试使用map。这就是为什么undefined不是函数(靠近“…posts.map…”)
发生的原因,因为当时posts
不是数组
有多种方法可以修复此错误,但最好保持一个单独的状态来处理错误,如下所示:
import React,{useState,useffect}来自“React”;
从“Axios”导入Axios;
从“react native”导入{View,Text,ScrollView};
从“./组件/PhotoPost”导入PhotoPost;
常量Home=()=>{
const[posts,setPosts]=useState([]);
const[error,setError]=useState(false);
useffect(()=>{
Axios.get(“http://127.0.0.1:3000/image_post/index")
。然后(res=>{
设置柱(res.data);
})
.catch(e=>{
设置错误(真);
//日志错误
控制台日志(e);
});
}, []);
返回(
{错误(
加载数据检查时出错。数据是否为数组?它正在控制台中返回一个对象。