无法在useState Hook中更新状态

huangapple go评论74阅读模式
英文:

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 &lt;Text className=&quot;font-bold text-lg&quot;&gt;{data.name}&lt;/Text&gt; 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 &#39;react-native&#39;
import React, { useEffect,useState } from &#39;react&#39;
import { Octicons } from &#39;@expo/vector-icons&#39;;
import { Pressable } from &#39;react-native&#39;;
import { FlatList } from &#39;react-native-gesture-handler&#39;;
import client from &#39;../sanity&#39;;
const Jobcard = () =&gt; {
//console.log(data);
const [services,setdata]=useState([]);
useEffect(()=&gt;
{
fetchdata();
},[services]);
const fetchdata=async()=&gt;
{
try {
const query=`*[_type == &quot;service&quot;]
{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=()=&gt;{
// service request code should come here
console.log(&quot;setrvice requested&quot;);
}
const renderpage=({data})=&gt;
{
&lt;View&gt;
&lt;Text className=&quot;font-bold text-lg&quot;&gt;{data.name}&lt;/Text&gt;  
&lt;Text className=&quot;font-bold&quot;&gt;{data.location}&lt;/Text&gt;
&lt;Text&gt;Workling hours:{data.workhour}&lt;/Text&gt;
&lt;View className=&quot;flex-row justify-center mt-3 space-x-6 items-center&quot;&gt;
&lt;View className=&quot;bg-green-500 px-2 py-2 rounded-md&quot;&gt;
&lt;Pressable className=&quot;&quot; android_ripple={{color:&quot;gray&quot;}} onPress={requestService}&gt;
&lt;Text className=&quot;text-center text-white&quot;&gt;Request Now&lt;/Text&gt;
&lt;/Pressable&gt;
&lt;/View&gt;
&lt;/View&gt;
&lt;/View&gt;
{/* image part */}
&lt;View&gt;
&lt;Image source={{uri:data.url}} className=&quot;h-24 w-24 rounded-full &quot;&gt;&lt;/Image&gt;
&lt;/View&gt;
}
return (
&lt;SafeAreaView&gt;
&lt;FlatList  data={services}
renderItem={renderpage}/&gt;
&lt;/SafeAreaView&gt;
)
}
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  [{&quot;accepter&quot;: {&quot;_ref&quot;: &quot;r7D6aPT0NrdX0UJBnRdPKr&quot;}, &quot;datetime&quot;: &quot;2023-06-17T17:13:00.000Z&quot;, &quot;location&quot;: {&quot;_type&quot;: &quot;geopoint&quot;, &quot;alt&quot;: -2, &quot;lat&quot;: 10.2365, &quot;lng&quot;: 123.36}, &quot;name&quot;: &quot;Plumber&quot;, &quot;requester&quot;: {&quot;_ref&quot;: &quot;d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4&quot;}, &quot;workhour&quot;: &quot;9-11&quot;}, {&quot;accepter&quot;: {&quot;_ref&quot;: &quot;wTURNjP62fuXRm3qPkJlYb&quot;}, &quot;datetime&quot;: &quot;2023-06-20T17:14:00.000Z&quot;, &quot;location&quot;: {&quot;_type&quot;: &quot;geopoint&quot;, &quot;alt&quot;: -3, &quot;lat&quot;: 56.325, &quot;lng&quot;: 12.56}, &quot;name&quot;: &quot;Nurse&quot;, &quot;requester&quot;: {&quot;_ref&quot;: &quot;d0d7a210-ba7d-4ff4-8b48-ddd662ceb9d4&quot;}, &quot;workhour&quot;: &quot;17-22&quot;}, {&quot;accepter&quot;: {&quot;_ref&quot;: &quot;wTURNjP62fuXRm3qPkJlYb&quot;}, &quot;datetime&quot;: &quot;2023-06-22T17:15:00.000Z&quot;, &quot;location&quot;: {&quot;_type&quot;: &quot;geopoint&quot;, &quot;alt&quot;: -3, &quot;lat&quot;: 12, &quot;lng&quot;: 46.35}, &quot;name&quot;: &quot;Mechanic&quot;, &quot;requester&quot;: {&quot;_ref&quot;: &quot;xnDGSrek1dgx2qitI95DEZ&quot;}, &quot;workhour&quot;: &quot;9-12&quot;}]

However, response is not updating. When I try to access the name property , It gives this error

TypeError: Cannot read property &#39;name&#39; 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 &#39;react-native&#39;;

you still need to use data?.example instead of data.example.<br>
also add a return statement in renderpage function just before &lt;view&gt;...&lt;/view&gt;

huangapple
  • 本文由 发表于 2023年6月22日 07:29:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定