FlatList不会渲染图像

时间:2019-10-23 01:06:42

标签: javascript reactjs react-native

我遇到了FlatList问题,我正在尝试使用从数据库中获取的数据来渲染图像。但是什么都没有出现。我可以从控制台看到数据,如您在此处看到的:

enter image description here

但是当我尝试访问照片时,它给了我两个错误:

  1. TypeError:无法读取未定义的属性“照片”
  2. 警告:无法在已卸载的组件上执行React状态更新。

现在我不知道为什么会给出不确定的信息,第二个错误我对此一无所知。

这是我对后端的请求:

    loadGames = async () => {
        const response = await api.get("/games")

        const  { games }  = response.data
        console.log(games)
        this.setState({ games })
    }

我在安装组件后立即发出请求,所以:

    componentDidMount() {
        this.loadGames();
        this.loadPlayers();
        console.log(this.state.games)     
    }

我已经声明了状态:

    state = {
        games:[],
        teams:[],
        players:[]
    }

现在FlatList:

<View style={{ height: 130, marginTop: 20, justifyContent:'center'}}>
    <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        data={this.state.games}
        keyExtractor={item => item._id}
        renderItem={({ item }) => this.renderGames(item)}
     />
</View>

我在renderItem中调用的方法:

renderGames = ({ item }) => {
    <View>
        <TouchableOpacity style={{flex:1/3, aspectRatio:1}} >
            <Image source={{ uri: `./image/games/${item.photo}` }} />
        </TouchableOpacity>
    </View>
}

有人知道我在哪里做错了吗?我该如何运作?

2 个答案:

答案 0 :(得分:1)

您的renderGames函数实际上未返回任何内容。

renderGames = ({ item }) => (
    <View>
        <TouchableOpacity style={{flex:1/3, aspectRatio:1}} >
            <Image source={{ uri: `./image/games/${item.photo}` }} />
        </TouchableOpacity>
    </View>
)

应该工作。

此外,您应该将该函数传递给renderItem道具,而不是创建自己的箭头函数,因为您将item作为参数传递,但是随后又破坏了另一个{{1 }}支持它:

item

答案 1 :(得分:0)

除了您的renderGames()函数不返回类似@RutherfordWonkington的内容之外,React Native Image组件不接受.ico(Windows图标)文件。

  

当前支持的格式为png,jpg,jpeg,bmp,gif,webp(仅适用于Android),psd(仅适用于iOS)   https://facebook.github.io/react-native/docs/image#source

相关问题