React / React Native:组件中的执行顺序

时间:2016-09-25 12:18:16

标签: reactjs react-native components

我无法弄清楚本机中的代码执行顺序。以下代码记录testtest 2,然后记录test 1。我想更改submittedURI的值。

 constructor(props) {
        super(props);
        this.state = {
            enterURI: ''
        };
    }

    onUriTextChanged(event) {
        this.setState({ enterURI: event.nativeEvent.text });
    }

    onSubmitPress() {
        var submittedURI = this.state.enterURI;
        console.log("test "+submittedURI);

        var url = encodeURIComponent(submittedURI), data = null;
        var xhr = new XMLHttpRequest();

        xhr.open("GET", "https://api.urlmeta.org/?url=" + url);
        xhr.send(data);
        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === this.DONE) {
           // console.log(this.responseText);
            var responseJSON = JSON.parse(this.responseText);
            submittedURI = responseJSON.meta.image;  
            console.log("test 1 "+submittedURI); 
          }
        });

        this.props.onURISubmit(submittedURI);
        console.log("test 2 "+submittedURI); 
    }

1 个答案:

答案 0 :(得分:0)

xhr.addEventListner("readystatechange", function() { ... })中的函数是一个回调函数,在请求为DONE后调用get。因此,在请求完成之前调用console.log("test 2 "+submittedURI);

请参阅此处的文档(https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

如果您想更改submittedURI,则必须在this.props.onURISubmit(submittedURI);回调中调用readystatechange功能。确保回调具有访问this.props的正确上下文。