【问题标题】:Why code doesnt work after handlerCall in .then of fetch in react-native?为什么在处理程序调用 .then 后,代码不起作用?
【发布时间】:2018-06-19 05:13:53
【问题描述】:

我正在使用 JIRA API 实现时间日志计算器。为什么我的代码在 React-Native 的 (.fetch) 的 (.then) 中的 callHandler 之后不起作用?在下面的代码中,我正在尝试控制台.log(“HIIIIIIIIIIII”),并尝试在上面设置状态以及调试器,它们都没有工作,既没有给出任何错误,也没有工作,handleJSONData 下面的所有行都不起作用虽然控制进入handleJSONData,为什么会发生这种情况?还有没有其他方法可以使用setState来设置程序中的进度状态以及在哪里?

感谢您的帮助。

import React, {Component} from 'react';
import {StyleSheet, Text, View, Animated} from 'react-native';
import Button from './Button';
import CardSection from './CardSection';
import MyDatePicker from "./MyDatePicker";
import Card from "./Card";
import ProgressBar from "./ProgressBar";


const handleStartDate = (delta) => {
    return (previousState, currentProps) => {
        return {...previousState, startDate: delta};
    };
};

const handleEndDate = (delta) => {
    return (previousState, currentProps) => {
        return {...previousState, endDate: delta};
    };
};

const handleProgressUpdate = () => {
    return (previousState, currentProps) => {
        return {...previousState, progress: this.state.dictionary["jatinverma"]};
    };
};

class AppComp extends Component {
    state = {startDate: null, endDate: null, jiraData: "", progress: 0, dictionary: {}};

    onStartDateChange = (date) => {
        this.setState(handleStartDate(date));
    };

    onEndDateChange = (date) => {
        this.setState(handleEndDate(date));
    };

    componentDidMount() {

        // debugger;
    }

    handleJSONData = (data) => {
        var keyArr = Object.keys(this.state.dictionary);

        for (var i = 0; i <= data.issues.length; i++) {

            fetch(data.issues[i].self, {
                method: 'get',
                headers: {
                    'Authorization': 'Basic ' + btoa('username:password'),
                }
            })
                .then((response) => response.json())
                .then(resData => {
                    var worklogsArr = resData.fields.worklog.worklogs;

                    for (var j = 0; j < worklogsArr.length; j++) {

                        var dtc = +Date.parse(worklogsArr[j].updated.slice(0, 10));
                        var startDate = +Date.parse(this.state.startDate);
                        var endDate = +Date.parse(this.state.endDate);
                        if ((dtc >= startDate) && (dtc <= endDate)) {
                            if (Object.keys(this.state.dictionary).indexOf(worklogsArr[j].author.name) >= 0) {
                                var nameDic = worklogsArr[j].author.name;
                                var abc = this.state.dictionary;
                                var ov = this.state.dictionary[nameDic];

                                abc[nameDic] = ov + worklogsArr[j].timeSpentSeconds;
                                this.setState({dictionary: abc});
                                console.log(this.state)
                            } else {
                                var nameDic = worklogsArr[j].author.name;
                                var abc = this.state.dictionary;

                                abc[nameDic] = worklogsArr[j].timeSpentSeconds;
                                this.setState({dictionary: abc});
                                console.log(this.state);
                            }
                        } else {

                        }

                    }
                });
        }

    }

    handleButtonClick = () => {
        this.setState({dictionary: {}});

        if (!global.btoa) {
            global.btoa = require('base-64').encode;
        }

        fetch('https://crossitc.atlassian.net/rest/api/latest/search?jql=updated>=' + this.state.startDate + '%20AND%20updated<=' + this.state.endDate, {
            method: 'get',
            headers: {
                'Authorization': 'Basic ' + btoa('username:password'),
            }
        })
            .then((response) => response.json())
            .then(responseData => {
                console.log(responseData);
                this.handleJSONData(responseData);

                 this.setState(handleProgressUpdate);
                console.log("HIIIIIIIIIIII" + this.state);
                debugger;
            });
    }

    render() {

        return (
            <Card>
                <CardSection>
                    <MyDatePicker onDateChangeRef={this.onStartDateChange} dateDateRef={this.state.startDate}/>
                    <Text> START={this.state.startDate}</Text>
                </CardSection>

                <CardSection>
                    <MyDatePicker onDateChangeRef={this.onEndDateChange} dateDate={this.state.endDate}/>
                    <Text> END={this.state.endDate}</Text>
                </CardSection>

                <CardSection>
                    <Button onPress={this.handleButtonClick}>CLICK!!!</Button>
                </CardSection>

                <CardSection>
                    <View style={styles.container}>
                        <View style={styles.progressContainer}>
                            <Text>Hours:</Text>
                            <ProgressBar progress={this.state.progress} row duration={500}/>
                            <Text>100%</Text>
                        </View>
                    </View>
                </CardSection>
            </Card>

        );
    }
};

const styles = {
    container: {
        flex: 1,
    },
    progressContainer: {
        alignItems: "center",
        flexDirection: "row"
    }
}

export default AppComp;

【问题讨论】:

    标签: reactjs react-native ecmascript-6 fetch setstate


    【解决方案1】:

    您没有将.catch() 语句链接到您的 Promise,因此您自然不会在控制台中看到任何错误。

    handleButtonClick = () => {
        this.setState({dictionary: {}});
    
        if (!global.btoa) {
            global.btoa = require('base-64').encode;
        }
    
        fetch('https://crossitc.atlassian.net/rest/api/latest/search?jql=updated>=' + this.state.startDate + '%20AND%20updated<=' + this.state.endDate, {
            method: 'get',
            headers: {
                'Authorization': 'Basic ' + btoa('username:password'),
            }
        })
            .then((response) => response.json())
            .then(responseData => {
                console.log(responseData);
                this.handleJSONData(responseData);
    
                 this.setState(handleProgressUpdate);
                console.log("HIIIIIIIIIIII" + this.state);
                debugger;
            })
            .catch(err => { console.log(err) })
    }
    

    同样,我建议将以下行添加到您的顶级 JavaScript 文件中:

    GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;

    这将允许您在开发人员工具中查看网络请求,然后您将能够查看您进行的每个 API 调用的请求/响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2016-03-16
      • 1970-01-01
      相关资源
      最近更新 更多