如何在TypeScript中渲染一个图像数组?

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

How to render an array of images in Typescript?

问题

以下是要翻译的内容:

I have an array of objects. Each object has two properties: The first one is a string and the second one is an array of urls. this is an example of the json that I am working with:

{
  data : [ {contentString : "eating sushi", ["url", "url", "url"] },... ]
}

I want to use a FlatList to render each url in an Image component. However, in visual studio code I find that the property source in the Image component is undelined and displays the following error:

Type '{ uri: IUrl; }' is not assignable to type 'ImageSourcePropType | undefined'.
      Types of property 'uri' are incompatible.
        Type 'IUrl' is not assignable to type 'string'.

As I understand, url is indeed a string because, as shown in the code below, the interface IUrl defines its data type as a string so I can not see why I am getting this error.

This is my code:

const Dashboard: React.FC <DashScreenProps> = (props) => {
   
    //interfaces
    //As mentioned above url is a string
    interface IUrl{
        url : string
    }

    interface IPost{
        contentString : string
        urls : IUrl[]
    }

    //local state variables
    const [arrayOfPosts, setArrayOfPosts] = useState<IPost[]>([])

    const getPostsFromFollowingUsers = async():Promise<boolean>=>{
        try {
            const response = await fetch(REMOTE_SERVER+`/userPost/getPostsFromFollowingUsers/${id}`)
            const parseResponse = await response.json()
            console.log('those are the posts', parseResponse)
            setArrayOfPosts(parseResponse.data)
        } catch (error) {
            console.log(error)
        }    
    }

    useEffect(()=>{
        getPostsFromFollowingUsers()
    },[]) 

    return(
        <View>
            {arrayOfPosts.map(post=>{
                //{contentString, urls}
                return(
                    <FlatList
                        data={post.urls}
                        renderItem={({item}) => {
                            return (
                                <Image source={{ uri: item }} style={{ width: 50, height: 50 }} />
                            )
                        }}  
                    />
                )
            })}
        </View>
    )
}

export default Dashboard
英文:

I have an array of objects. Each object has two properties: The first one is a string and the second one is an array of urls.
this is an example of the json that I am working with:

{
  data : [ {contentString : &quot;eating sushi&quot;, [&quot;url&quot;, &quot;url&quot;, &quot;url&quot;] },... ]
}

I want to use a FlatList to render each url in an Image component. However, in visual studio code I find that the property source in the Image component is undelined and displays the following error:

Type &#39;{ uri: IUrl; }&#39; is not assignable to type &#39;ImageSourcePropType | undefined&#39;.
      Types of property &#39;uri&#39; are incompatible.
        Type &#39;IUrl&#39; is not assignable to type &#39;string&#39;.

As I understand, url is indeed a string because, as shown in the code below, the interface IUrl defines its data type as a string so I can not see why I am getting this error.
This is my code:

const Dashboard : React.FC  &lt;DashScreenProps&gt;= (props)=&gt;{
   
    
    //interfaces
    //As mentioned above url is a string
    interface IUrl{
        url : string
    }

    interface IPost{
        contentString : string
        urls : IUrl[]
    }
    
    
   

    //local state variables
    const [arrayOfPosts, setArrayOfPosts] = useState&lt;IPost[]&gt;([])

   

    
    const getPostsFromFollowingUsers = async():Promise&lt;boolean&gt;=&gt;{
        try {
            const response = await fetch(REMOTE_SERVER+`/userPost/getPostsFromFollowingUsers/${id}`)
            const parseResponse = await response.json()
            console.log(&#39;those are the posts&#39;, parseResponse)
            setArrayOfPosts(parseResponse.data)
            
        } catch (error) {
            console.log(error)
            
        }    
        
    }

    
    useEffect(()=&gt;{
        getPostsFromFollowingUsers()
    },[]) 
    return(
            &lt;View&gt;
                
                {arrayOfPosts.map(post=&gt;{
                    //{contentString, urls}
                    return(
                        &lt;FlatList
                        data = {post.urls}
                        renderItem={({item}) =&gt; {
                            return (
                                &lt;Image source={{ uri: item }} style={{ width: 50, height: 50 }} /&gt;
                            )
                        }}  
                        /&gt;
                    )
                })}
                 
                
            &lt;/View&gt;
    )
}

export default Dashboard

答案1

得分: 0

尝试更改您的 IPost 接口声明:

interface IPost {
    contentString: string;
    urls: string[];
}
英文:

Try to change your IPost interface declaration:

interface IPost{
    contentString : string
    urls : string[]
}

答案2

得分: 0

你正在提取错误的键数据 post.urlsurls 在给定的数据中不存在,而且数据是对象类型,而不是数组,.map 只在数组的情况下运行

{
  data: [{ contentString: "eating sushi", ["url", "url", "url"] }, ...]
}

使用以下数据,一切都会正常工作

[
  {
    contentString: "eating sushi",
    url: [
      "https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516__340.jpg",
      "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQbJVpOdtk96FIiNKr9o2eVdz6pebpXb2n3UO6MjRDGABy-1EoDIjhwog9ACA7ez0RYH7Q&amp;usqp=CAU",
      "https://cdn.xxl.thumbs.canstockphoto.com/test-concept-picture_csp17279717.jpg"
    ]
  }
]

或者尝试更改你的 IPost 接口声明:

interface IPost {
  contentString: string;
  urls: string[]; // 此处类型错误
}
英文:

You are fetching the wrong key data post.urls urls not exist in the given data also the data is an object type not an array in the .map only runs in case of an array

{
  data : [ {contentString : &quot;eating sushi&quot;, [&quot;url&quot;, &quot;url&quot;, &quot;url&quot;] },... ]
}

Use this data then everything will be working fine

[
    {
      contentString: &quot;eating sushi&quot;,
      url: [
        &quot;https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516__340.jpg&quot;,
        &quot;https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQbJVpOdtk96FIiNKr9o2eVdz6pebpXb2n3UO6MjRDGABy-1EoDIjhwog9ACA7ez0RYH7Q&amp;usqp=CAU&quot;,
        &quot;https://cdn.xxl.thumbs.canstockphoto.com/test-concept-picture_csp17279717.jpg&quot;
      ]
    }
  ]

or Try to change your IPost interface declaration:

interface IPost{
    contentString : string
    urls : string[] // wrong type here
}

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

发表评论

匿名网友

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

确定