Reetch-Native setState在fetch()期间不更新

时间:2018-04-10 15:13:45

标签: reactjs react-native

我的表中有3条记录,我可以看到应用程序将记录提取到我的遥控器,因为我在console.log响应。我的问题是它不会显示该项目。

我知道我在FlatList中正确定义了列,因为如果我将设置per_page=1,这意味着每个请求都会拉1条记录。它会显示,但只有2条记录才会显示最后一条记录,如果设置为per_page=30则不会显示任何内容。我的setState()在响应期间有问题吗?。我听说setSate不可变。我可以在我的代码中应用setsate的updater函数。我仍然很新鲜的反应本机我希望有人会帮助我。

我试图这样做,但没有运气!..这也很重要我在其他页面使用react-redux然后在这个屏幕中我没有使用只处理状态。 ?...请帮助我反应原生专家。

this.setState({
                        page: this.getParameterByName('page', res.next_page_url),
                        data: this.state.page === 1 ? res.data : [...this.state.data, ...res.data],
                        error: res.error || null,
                        loading: false,
                        refreshing: false,
                        last_page: res.last_page
                    },()=>{
                       return this.state;
                   });

这是我的完整代码

import React, { Component } from 'react';
import {ScrollView, Text, View, Button, FlatList, ActivityIndicator} from 'react-native';
import { List, ListItem, Icon } from "react-native-elements";
import {connect} from "react-redux";
import numeral from "numeral";
import Moment from 'react-moment';
import moment from 'moment';

class Screen1 extends Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            data: [],
            page: 1,
            per_page: 30,
            order_by:'id',
            sort_by:'asc',
            error: null,
            refreshing: false,
            param:'',
            last_page:''
        };
    }

    componentDidMount() {
        this.makeRemoteRequest();
    }

    makeRemoteRequest = () => {

        const {page, per_page,order_by,sort_by } = this.state;
        const url = `http://myapp.com/api/mobile/credit?page=${page}&api_token=${this.props.token}&per_page=${per_page}&order_by=${order_by}&sort_by=${sort_by}`;
        console.log("the url",url);

        this.setState({ loading: true });
        setTimeout(()=>{
            fetch(url)
                .then(res => res.json())
                .then(res => {
                   console.log("the page is =",this.getParameterByName('page',res.next_page_url));
                    this.setState({
                        page:this.getParameterByName('page',res.next_page_url),
                        data: this.state.page === 1 ? res.data : [...this.state.data,...res.data],
                        error: res.error || null,
                        loading: false,
                        refreshing: false,
                        last_page: res.last_page
                    });

                })
                .catch(error => {
                    this.setState({ error, loading: false });
                });
        },1500);
    };

    handleRefresh = () => {

        if( this.state.page) {
            if (this.state.page <= this.state.last_page) {
                this.setState(
                    {
                        refreshing: true,
                        page: this.state.page
                    },
                    () => {

                        this.makeRemoteRequest();


                    }
                );
            }
        }

    };

    getParameterByName = (name,url) =>{
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return  parseInt(decodeURIComponent(results[2].replace(/\+/g, " ")), 10);
    };
    handleLoadMore = () => {

        if( this.state.page){
            if( this.state.page <= this.state.last_page ){
                this.setState(
                    {

                        page: this.state.page
                    },
                    () => {
                        this.makeRemoteRequest();
                    }
                );

            }else{
                console.log("cannot handle more",this.state.page)
            }
        }else{
            console.log("page is null");
        }

    };

    renderSeparator = () => {
        return (
            <View
                style={{
                    height: 1,
                    width: "86%",
                    backgroundColor: "#CED0CE",
                    marginLeft: "14%"
                }}
            />
        );
    };

    renderHeader = () => {
        return (
            <View >
                <Text h1
                      style={{
                          color: 'blue',
                          fontWeight: 'bold',
                          textAlign: 'center',
                          fontSize: 30,
                          backgroundColor: "#CED0CE",

                      }}
                >{ numeral(this.props.thetotalcredit).format("#,##0.00") }</Text>
            </View>
        );
    };

    renderFooter = () => {
        if (!this.state.loading) return null;

        return (
            <View
                style={{
                    paddingVertical: 20,
                    borderTopWidth: 1,
                    borderColor: "#CED0CE"
                }}
            >
                <ActivityIndicator animating size="large" />
            </View>
        );
    };

    render() {

        return (


                <FlatList

                    data={this.state.data}
                    keyExtractor = {(item, index) => index.toString()}
                    renderItem={({ item }) => (
                        <ListItem

                            title= { numeral(item.amountcredit).format("#,##0.00") }
                            subtitle= { moment(item.creditdate).format("MMM DD, YYYY") }

                            containerStyle={{ borderBottomWidth: 0 }}
                        />
                    )}

                    extraData={this.state.data}
                    ItemSeparatorComponent={this.renderSeparator}
                    ListHeaderComponent={this.renderHeader}
                    ListFooterComponent={this.renderFooter}
                    refreshing={this.state.refreshing}
                    onRefresh={this.handleRefresh}
                    onEndReached={this.handleLoadMore}
                    onEndReachedThreshold={0.5}
                    stickyHeaderIndices={[0]}
                />

        );
    }
    }

    const mapStateToProps = (state) => {

        return {

            username: state.auth.username,
            token:state.auth.token,
            thetotalcredit:state.auth.total_credit



        };
    };

    export default connect(mapStateToProps)(Screen1);

0 个答案:

没有答案