ReactNative 不渲染微调器并渲染其他不需要的加载组件

问题描述 投票:0回答:1

我正在尝试使用 ActivityIndicator 和 ReactNative 来加载微调器。我模拟了rest api来看看spinner是否有效。问题是,尽管我正在使用 ActivityIndicator,但我看到了我尚未创建的组件,而 isLoading 为 true。

我看到的组件左上角有文本“正在加载...”。

加载组件

模拟端点加载时间的函数:

async fetchFishDetails(fishId: number): Promise<ApiResponse<any>> {
        let fish: Fish | undefined
        let user: any | undefined

        fish = this.user1.fishes.find(fish => fish.id === fishId)
        user = this.user1
        if (fish === undefined) {
            fish = this.user2.fishes.find(fish => fish.id === fishId);
            user = this.user2
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        
        return {
            status: 200,
            body: {fishDetails: fish, user: user}
        }
    }

处理上述函数响应的函数:

export const getFishDetails = async (fishId: number): Promise<ServiceResponse<any>> => {
    console.debug('getFishDetails(), fishId=', fishId);

    try {
        const response = await fishRestApi.fetchFishDetails(fishId);
        
        if (response.status === 200) {
            return new ServiceResponse(Type.SUCCESS, response.body);
        } else {
            console.error('Error occurred fetching fish from backend')
            return new ServiceResponse(Type.FAIL, undefined);
        }
    } catch (error) {
        console.error('Error occurred getting fish, err=', error);
        return new ServiceResponse(Type.FAIL, undefined);
    }
};

在组件中获取数据

    useEffect(() => {
        setIsLoading(true)
        console.log('start loading')
        getFishDetails(fishId)
            .then(response => {
                if (response.type === Type.SUCCESS) {
                    const {fishDetails, user} = response.body;
                    setFishDetails(fishDetails);
                    setUser(user);
                    setProfilePictureUri(user.picture ? {uri: user.picture} : require('../assets/user-default.png'));
                } else {
                    console.log('Failed to get fish details');
                }
            })
            .catch(err => {
                console.error('Error fetching fish details:', err);
            })
            .finally(() => {
                setIsLoading(false);
                console.log('loading ended')
            })

    }, [fishId]);

返回的视图

return (
        <ScrollView style={styles.container}>
            {isLoading ? (<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator size="large" animating={true}/>
            </View>) : <View style={styles.content}> ....  </View>

对于有关“正在加载...”组件的解释以及所有其他建议,我们将不胜感激。

我尝试搜索谷歌和有关该组件的文档,但找不到任何内容。

javascript react-native react-hooks
1个回答
0
投票

你可以试试这个

if(isLoading){
   <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    <ActivityIndicator size="large" animating={true}/>
   </View>
}else{
  <View style={styles.content}> ....  </View>
}
© www.soinside.com 2019 - 2024. All rights reserved.