React Native - Invariant Violation

时间:2018-03-13 11:16:21

标签: javascript react-native invariants activity-indicator

所以我已经建立了一个Spinner组件,并且我一直受到不变的违规行为。

组件:

import React from 'react';
import { View, ActivityIndicator } from 'react-native';

const Spinner = ({ size }) => {
    return ( 
        <View style={ styles.spinnerStyle }>
            <ActivityIndicator size={ size || 'large' } />
        </View>
    );
};

const styles = {
    spinnerStyle: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
};

export { Spinner };

我在这里使用它:

// Import libs
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import Axios from 'axios';
import AlbumDetail from './albumDetail';
import { Spinner } from './common';

// Create component
class AlbumList extends Component {
    state = {
        albums: [],
        loading: true
    }

    componentWillMount() {
        Axios.get('xxxxx.json').then(response =>
            this.setState({
                albums: response.data,
                loading: false
            })
        );
    }

    renderAlbums() {
        if ( this.state.loading ) {
            return <Spinner size='small'></Spinner>
        }

        return this.state.albums.map( album => 
            <AlbumDetail key={album.title} album={album}/>
        )
    }

    render() {
        return (
            <ScrollView>
                {this.renderAlbums()}
            </ScrollView>
        );
    }
}

// Export the component for the rest to use
export default AlbumList;

完整错误是:不变违规:元素类型无效:需要一个字符串。

我尝试添加:

if ( this.state.loading ) {
   return (
       <View style={styles.loading}>
          <ActivityIndicator size='large' />
        </View>
    )
 }

这很有效。但当用作组件时,它不想玩。任何帮助都会很棒。感谢

2 个答案:

答案 0 :(得分:1)

公共文件夹中的索引没有:

export * from './spinner';

答案 1 :(得分:0)

您还可以将导出声明更改为: 导出默认Spinner;

并将声明导入: 从&#39; ./ common / Spinner&#39;;

导入Spinner

但我个人在我的公共文件夹中使用index.js来存储所有导出,在这种情况下: export * from ./Spinner;

然后我必须通过调用来导入它: 从&#39; ./ common&#39;;

导入{Spinner}