英文:
Unable to update the state in useState Hook
问题
这是我的代码。我正在使用Sanity进行内容管理并开发React Native应用程序。这里的API调用返回了正确的值,但setdata
未更新状态services
。因此,当我尝试访问这里的<Text className="font-bold text-lg">{data.name}</Text>
时,会出现错误。请帮助我解决这个错误。错误日志如下所示。我在另一个组件中像这样调用这个组件:{request? <PostJob></PostJob>: <Jobcard ></Jobcard>}
主要代码。
import { StyleSheet, Text, View, Image, SafeAreaView } from 'react-native'
import React, { useEffect, useState } from 'react'
import { Octicons } from '@expo/vector-icons';
import { Pressable } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import client from '../sanity';
const Jobcard = () => {
const [services, setdata] = useState([]);
useEffect(() => {
fetchdata();
}, [services]);
const fetchdata = async () => {
try {
const query = `*[_type == "service"]
{accepter{_ref},requester{_ref},datetime,name,location,workhour}`;
const response = await client.fetch(query);
console.log(response);
setdata(response);
console.log(services);
} catch (error) {
console.log(error);
}
}
const requestService = () => {
console.log("service requested");
}
const renderpage = ({ data }) => {
return (
<View>
<Text className="font-bold text-lg">{data.name}</Text>
<Text className="font-bold">{data.location}</Text>
<Text>Working hours: {data.workhour}</Text>
<View className="flex-row justify-center mt-3 space-x-6 items-center">
<View className="bg-green-500 px-2 py-2 rounded-md">
<Pressable className="" android_ripple={{ color: "gray" }} onPress={requestService}>
<Text className="text-center text-white">Request Now</Text>
</Pressable>
</View>
</View>
</View>
{/* 图片部分 */}
<View>
<Image source={{ uri: data.url }} className="h-24 w-24 rounded-full "></Image>
</View>
);
}
return (
<SafeAreaView>
<FlatList data={services} renderItem={renderpage} />
</SafeAreaView>
)
}
export default Jobcard
const styles = StyleSheet.create({})
在useEffect
中,我调用了fetchdate()
函数。API调用成功并返回了这个响应,但response
没有更新。当我尝试访问name
属性时,它会引发以下错误:
TypeError: Cannot read property 'name' of undefined
我阅读了一些帖子,建议使用useEffect()
,但我已经在使用了。非常感谢您的帮助。
英文:
This is my code. I'm using sanity for content management and developing react native app. Here the API call is returning correct value however setdata is not updating the state services. So when I try to access this which is here <Text className="font-bold text-lg">{data.name}</Text>
It gives error. Please help me solving this error. error log is mentioned below. I'm calling this component in another component like this `{request? <PostJob></PostJob>: <Jobcard ></Jobcard>}'
Main code.
import { StyleSheet, Text, View,Image, SafeAreaView } from 'react-native'
import React, { useEffect,useState } from 'react'
import { Octicons } from '@expo/vector-icons';
import { Pressable } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import client from '../sanity';
const Jobcard = () => {
//console.log(data);
const [services,setdata]=useState([]);
useEffect(()=>
{
fetchdata();
},[services]);
const fetchdata=async()=>
{
try {
const query=`*[_type == "service"]
{accepter{_ref},requester{_ref},datetime,name,location,workhour}`;
const response= await client.fetch(query);
console.log(response);
setdata(response);
console.log(services);
} catch (error) {
console.log(error);
}
}
const requestService=()=>{
// service request code should come here
console.log("setrvice requested");
}
const renderpage=({data})=>
{
<View>
<Text className="font-bold text-lg">{data.name}</Text>
<Text className="font-bold">{data.location}</Text>
<Text>Workling hours:{data.workhour}</Text>
<View className="flex-row justify-center mt-3 space-x-6 items-center">
<View className="bg-green-500 px-2 py-2 rounded-md">
<Pressable className="" android_ripple={{color:"gray"}} onPress={requestService}>
<Text className="text-center text-white">Request Now</Text>
</Pressable>
</View>
</View>
</View>
{/* image part */}
<View>
<Image source={{uri:data.url}} className="h-24 w-24 rounded-full "></Image>
</View>
}
return (
<SafeAreaView>
<FlatList data={services}
renderItem={renderpage}/>
</SafeAreaView>
)
}
export default Jobcard
const styles = StyleSheet.create({})
In the useEffect
I'm calling the function fetchdate()
. The API call is successful and it returns this
LOG [{"accepter": {"_ref": "r7D6aPT0NrdX0UJBnRdPKr"}, "datetime": "2023-06-17T17:13:00.000Z", "location": {"_type": "geopoint", "alt": -2, "lat": 10.2365, "lng": 123.36}, "name": "Plumber", "requester": {"_ref": "d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4"}, "workhour": "9-11"}, {"accepter": {"_ref": "wTURNjP62fuXRm3qPkJlYb"}, "datetime": "2023-06-20T17:14:00.000Z", "location": {"_type": "geopoint", "alt": -3, "lat": 56.325, "lng": 12.56}, "name": "Nurse", "requester": {"_ref": "d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4"}, "workhour": "17-22"}, {"accepter": {"_ref": "wTURNjP62fuXRm3qPkJlYb"}, "datetime": "2023-06-22T17:15:00.000Z", "location": {"_type": "geopoint", "alt": -3, "lat": 12, "lng": 46.35}, "name": "Mechanic", "requester": {"_ref": "xnDGSrek1dgx2qitI95DEZ"}, "workhour": "9-12"}]
However, response
is not updating. When I try to access the name property , It gives this error
TypeError: Cannot read property 'name' of undefined
I read some posts which suggested to use useEffect() which I'm already using.
Help is very much appreciated.
答案1
得分: 2
你需要从react-native
中导入FlatList
,而不是使用另一个包中的组件,这不是同一件事情:
import { FlatList } from 'react-native';
你仍然需要使用data?.example
而不是data.example
。
还要在renderpage
函数中在<view>...</view>
之前添加一个return
语句。
英文:
you have to import FlatList
from react-native
instead.<br> here you are using another component from another package it is not the same thing:
import { FlatList } from 'react-native';
you still need to use data?.example
instead of data.example
.<br>
also add a return
statement in renderpage
function just before <view>...</view>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论