【问题标题】:Invalid attempt to spread non-iterable instance in Flatlist React Native在 Flatlist React Native 中传播不可迭代实例的尝试无效
【发布时间】:2019-07-01 02:39:03
【问题描述】:

我正在尝试使用平面列表进行无限滚动加载,例如 instagram 和 twitter。在 youtube https://www.youtube.com/watch?v=WcGd8VkRc48 上找到了一个视图,它与这个 api 和函数完美配合。我将我的逻辑应用于同一个 api 并工作。但是当我将它应用到我的 API 时,它给了我错误“传播不可迭代实例的无效尝试”

所以,这就是交易。 componentDidMount() 完美地完成了抓取并且效果很好。现在 flatlist 提供了刷新整个列表或继续加载后续帖子的选项,例如我们在 instagram 和时间线应用中所做的。

刷新整个列表,向下滑动非常完美。但是当我到达列表的末尾时,我调用了一个加载下一个项目的函数,但此时出现了错误。它必须与对象数组有关,但之前的视频以同样的方式完美运行!请帮忙

state = {
        isLoading: true,
        refreshing:false,
        page:0,
        loading: false,
        data:[],
        photoLoading: false,
        photoLoading2: false,
  };

renderItem = ({item}, i) => {'this render item works and has no problem}

_onRefresh = async () =>{
    this.setState({refreshing: true});
    const tk = await AsyncStorage.getItem('userToken');
    console.log(tk);
    fetch('MY API LINK /?skip=0&limit=5', {
        method: 'GET',
        headers:{
            'Content-type':'application/json',
            'x-access-token': tk
        }
    })
        .then((response) => response.json())
        .then((responseJson) => {
            if(responseJson.status === 'success'){
                console.log(responseJson);
                this.setState(state => ({
                    data: responseJson.data,
                    refreshing: false
                }));
                console.log('PRINT SUCCESS RESULT OF REFRESH')
                console.log(this.state.data)
            }
        })
        .catch((error)=>{
            console.log('ERROR IN REFRESHING');
            console.log(error)
        })

};

componentDidMount = async () => {    
    this.setState({ isLoading: true });
    const tk = await AsyncStorage.getItem('userToken');
    fetch('MY API LINK /?skip=0&limit=5', {
        method: 'GET',
        headers:{
            'Content-type':'application/json',
            'x-access-token': tk
        }
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson);
            this.setState(state => ({
                data: responseJson.data,
                isLoading: false,
                refreshing: false
            }));
            console.log('PRINT RESULT')
            console.log(this.state.data)
        })
        .catch((error)=>{
            console.log('ERROR');
            console.log(error)
        })
    // this.fetchData()
}

fetchData = async ()=>{
    this.setState({loading: true})
    const tk = await AsyncStorage.getItem('userToken');
    fetch(`MY API LINK /?skip=${this.state.page}&limit5`
    , {
        method: 'GET',
        headers:{
            'Content-type':'application/x-www-form-urlencoded',
            'x-access-token': tk
        }
    }
    ).then((response) => response.json())
    .then((responseJson) => {
        this.setState(state => ({ 
            data: [...state.data, ...responseJson.data], 
            loading: false, 
            // isLoading:false
        }));
    })
    .catch((error) => {
        console.log(error);
    })
}

handleEnd = () => {
    this.setState(state => ({ page: state.page + 1 }), () => this.fetchData());
};

render() {
    return (
        this.state.isLoading ?
            <View style={{flex:1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator size='large' color={'black'} animating/>
            </View>
        :
        <View style={styles.container}>
            <FlatList
                data={this.state.data}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this._onRefresh}
                    />
                }
                keyExtractor={(x, i) => i.toString()}
                onEndReached={() => this.handleEnd()}
                onEndReachedThreshold={0}
                ListFooterComponent={() =>
                this.state.loading ? 
                    null
                    : 
                    <ActivityIndicator size="large" animating />
                }
                renderItem={this.renderItem}
            />
        </View>
    );
}}

【问题讨论】:

    标签: javascript api react-native object react-native-flatlist


    【解决方案1】:

    我发现了错误,在 fetchData 函数中我错过了参数中的“=”以获得我想要的结果。

    代码现在很好用!希望它可以帮助任何阅读并想要在 React Native 中使用 FlatList 进行无限滚动的人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2019-06-25
      • 2019-07-18
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多