【问题标题】:React/React Native: Execution order in a ComponentReact/React Native:组件中的执行顺序
【发布时间】:2017-02-02 20:17:34
【问题描述】:

我无法弄清楚 react native 中的代码执行顺序。以下代码记录了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); 
    }

【问题讨论】:

    标签: reactjs react-native components


    【解决方案1】:

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

    在此处查看文档 (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange)

    如果您想更改submittedURI,您将不得不在readystatechange 回调中调用this.props.onURISubmit(submittedURI); 函数。确保回调具有访问this.props 的正确上下文。

    【讨论】:

    • 对。谢谢您的帮助。当我在readystatechange 中调用this.props.onURISubmit(submittedURI); 时,我得到了undefined is not an object (evaluating 'this.props.onURISubmit')
    • 通过将this 存储在另一个变量中来解决它。
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2022-11-08
    相关资源
    最近更新 更多