【问题标题】:render function not rendering anything React Native渲染函数不渲染任何东西 React Native
【发布时间】:2019-03-21 01:32:00
【问题描述】:

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

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>
        )
    }
}

【问题讨论】:

  • 你必须从你的renderHorizontalContents 函数中返回一些东西。使用return rowItems.map((rowItem, index) =&gt; {...}
  • 好收获.. 现在工作.. 非常感谢 :) @nrgwsth

标签: javascript reactjs react-native axios


【解决方案1】:

您的renderHorizontalContents() 应该返回列表:

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

此外,从 React 16.3 开始,React 团队建议不要使用 componentWillMount()。您应该在componentDidMount() LifeCycle 挂钩中获取数据。

更多关于componentWillMount()弃用:

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

【讨论】:

    【解决方案2】:

    试试这个。问题是 renderHorizo​​ntalContents() 没有返回,所以你必须返回 map 为你返回的元素

    另外关于添加键,如果 items 数组包含每个对象的唯一 id,则使用它作为推荐的键。如果您没有来自数据的唯一 ID,则索引始终是第二选择。此外,在添加索引作为键时,您应该像下面那样添加一些东西,而不是直接添加索引作为键。

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

    【讨论】:

    • 你不需要 if,如果你有长度它已经是一个数组,所以不会循环它们
    • @JoeWarner 同意你的看法
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2017-10-08
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多