渲染中没有返回任何内容:React Native

时间:2018-03-30 16:22:19

标签: android reactjs react-native

我希望从我的JSON API通过 Image.prefetch() 缓存图片,但它会抛出错误" Invariant违规:StaticRender():Android模拟器中没有从渲染" 返回任何内容,但实际上我已将其返回。 (我使用 react-native 命令,而不是create-react-native-app或expo)

  

组件:

import React, { Component } from 'react';
import {AppRegistry, Image, Button, Text, View, ListView, StyleSheet} from 
'react-native';

export default class Shayari extends Component {
    constructor() {
        super();
        const imgApi = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            userDataSource: imgApi,
        };
    }

    componentDidMount(){
        this.fetchShayari();
    }

    fetchShayari(){
        fetch('http://myapiurl.com')
            .then((response) => response.json())
            .then((response) => {
                this.setState({
                    userDataSource: this.state.userDataSource.cloneWithRows(response)
                });
        });
    }

    renderRow(shayariImg, sectionId, rowId, highlightRow) {

        let urlOfImages = [shayariImg.url];

        let preFetchTasks = []; 

        urlOfImages.forEach((p) => {
            preFetchTasks.push(Image.prefetch(p));
        });

        Promise.all(preFetchTasks).then((results) => {
            let downloadedAll = true;
            results.forEach((result) => {
                if(!result) {
                    //error occurred downloading a pic
                    downloadedAll = false;
                }
            })

            if(downloadedAll) {

                return(
                   <View>
                        <Image source={urlOfImages} />
                    </View>
                );
            }
        })
    }

    render() {
        return(
            <ListView 
                dataSource={this.state.userDataSource}
                renderRow={this.renderRow.bind(this)}
            />
        );
    }
}

AppRegistry.registerComponent('mehfileishq', () => Shayari);

如果我不使用缓存图像,一切都运行良好。

1 个答案:

答案 0 :(得分:0)

渲染方法需要渲染或null。 在这种情况下如果(!downloadedAll),那么我们就不会返回任何内容。

将else条件添加到downloadedAll并从那里返回一些内容。这样我们总是返回一些渲染方法。

       if(downloadedAll) {

            return(
               <View>
                    <Image source={urlOfImages} />
                </View>
            );
        }

        else {
            return(
               <View>
                    <Text> Fetching image.... </Text>
                </View>
            );
        }