在平面列表中反应本地动态图像

时间:2020-09-16 13:32:39

标签: javascript react-native

此处是初学者的问题,因此轻松进行。 我一直在尝试使用https://jsonplaceholder.typicode.com/photos中的网址在我的列表中呈现一些图片,我首先尝试在文本中添加标题,但似乎可以正常工作。 但是当我尝试使用网址无效时,我的代码:

export default function Home() {
     const [data, setData] = useState([]);
      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/photos')
          .then((res) => res.json())
          .then((response) => setData(response))
          .catch((error) => {
               console.log(error);
             });
      });
     return (
        <View style={styles.containermainstyle}>
          <View style={styles.headerstyle}>
            <TextInput style={styles.inputstyle} placeholder={'product...'} />
            <TouchableOpacity>
              <Text>Filtres</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.mainstyle}>
            <FlatList
              data={data}
              renderItem={({ item }) => {
              <View style={{flex:1, flexDirection: 'row'}}>  
                <Image
                  style={styles.imagestyle}
                  source={{uri: item.url }}
                />;
              </View>
              }}
            />
          </View>
        </View>
      );
    }

1 个答案:

答案 0 :(得分:2)

render iphone

好像您的renderItem函数不正确,因为它缺少return (<JSX />)

而不是...

({ item }) => {
<View style={{ flex:1, flexDirection: 'row' }}>  
  <Image
    style={styles.imagestyle}
    source={{ uri: item.url }}
  />;
</View>
}

应该是

({ item }) => {
  return (
  <View style={{ flex:1, flexDirection: 'row' }}>  
    <Image
      style={styles.imagestyle}
      source={{ uri: item.url }}
    />
  </View>
  )
}

还请注意,如果您不想不断进行重新提取,useEffect应该有一个空的依赖项数组。

示例修复

import React, { useState, useEffect } from "react"
import { View, Image, FlatList, Text, TouchableOpacity } from "react-native"

export default function App() {
  const [data, setData] = useState([])
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((res) => res.json())
      .then((response) => {
        setData(response)
      })
      .catch((error) => {
        console.log(error)
      })
  }, [])

  const renderItem = ({ item }) => {
    console.log(item)
    return (
      <View style={{ flex: 1, flexDirection: "row" }}>
        <Image style={{ height: 100, width: 100 }} source={{ uri: item.url }} />
      </View>
    )
  }

  return (
    <View>
      <View>
        <FlatList data={data} renderItem={renderItem} />
      </View>
    </View>
  )
}
相关问题