首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >render函数不渲染任何React Native

render函数不渲染任何React Native
EN

Stack Overflow用户
提问于 2018-10-16 21:36:19
回答 2查看 1.8K关注 0票数 3

屏幕上未显示任何内容。不知道为什么会这样,任何地方都没有错误。想知道为什么屏幕上什么都没有显示。从API中正确获取数据。代码如下:

代码语言:javascript
复制
import React, { Component } from 'react';
import { StyleSheet, ScrollView, TouchableOpacity, Text, View } from 'react-native';
import { Container, Content, Grid, Row, Col } from 'native-base';
import axios from 'axios';
import ItemCard  from '../components/ItemCard';

export default class ItemHorizontalScreen  extends Component {
    constructor(props) {
        super(props)
        this.state = {
            items: []
        }
    }

    componentWillMount() {
        axios.get('http://rallycoding.herokuapp.com/api/music_albums').then(response => 
            this.setState({
                items: response.data
            }))
        .catch((error) => {
            console.error(error);
        })
    }

    renderHorizontalContents() {
        const rowItems = this.state.items
        rowItems.map((rowItem, index) => {
            return (
                <TouchableOpacity key={index}>
                    <Text>{rowItem.title}</Text>
                </TouchableOpacity>
            )
        })
    } 

    render() {
        return (
            <View>
            {this.renderHorizontalContents()}
            </View>
        )
    }
}
EN

回答 2

Stack Overflow用户

发布于 2018-10-16 21:39:04

您的renderHorizontalContents()应返回以下列表:

代码语言:javascript
复制
renderHorizontalContents() {
    const rowItems = this.state.items
    return rowItems.map((rowItem, index) => {
        return (
            <TouchableOpacity key={index}>
                <Text>{rowItem.title}</Text>
            </TouchableOpacity>
        )
    })
} 

另外,半相关的,从React 16.3React团队建议不要使用componentWillMount()。您应该在componentDidMount() LifeCycle钩子中获取数据。

有关componentWillMount()弃用的更多信息:

https://github.com/styled-components/styled-components/issues/1575

票数 3
EN

Stack Overflow用户

发布于 2018-10-16 21:39:36

尝尝这个。问题是renderHorizontalContents()没有返回,所以您必须返回映射为您返回的元素

另外,关于添加key,如果items数组包含每个对象的唯一id,那么建议使用它作为key。如果数据中没有唯一的id,那么索引始终是第二个选择。另外,当添加索引作为键时,你应该像我在下面做的那样添加一些东西,而不是直接添加索引作为键。

代码语言:javascript
复制
renderHorizontalContents() {
        const { items } = this.state;
           return items.map((rowItem, index) => {
            return (
                <TouchableOpacity key={"Key"+index}>
                    <Text>{rowItem.title}</Text>
                </TouchableOpacity>
            )
        })
    } 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52836767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档