Javascript react component this.value即使在';人满为患

Javascript react component this.value即使在';人满为患,javascript,reactjs,es6-promise,Javascript,Reactjs,Es6 Promise,这里是我拥有的React组件的简化版本: class Example extends Component { constructor(props) { super(props); this.state = {key : 10 }; this.value = null; } componentDidMount() { this.fetchValueFromServer(); this.fetc

这里是我拥有的React组件的简化版本:

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {key : 10 };
        this.value = null;
    }

    componentDidMount() {
        this.fetchValueFromServer();
        this.fetchSecondValueFromServer();
    }

    fetchValueFromServer() {
        fetch_value_from_server(this.state.key).then( (value) => {
            this.value = value;     
        }); 
    }

    fetchSecondValueFromServer() {
        is_ready(this.value).then(() => {
            console.log("there");       
        }); 
    }

}
我希望看到console.log(“there”)被打印出来,但是
这个.value
始终保持为空,即使在
fetchValueFromServer
中设置了。为什么会这样? 如果你想知道
准备好了吗
看起来很好,这是一个简单的承诺:

function is_ready(variable) {

    return new Promise((resolve, reject) => {
        let interval = setInterval(() => 
        { 
            if (variable) {
                clearInterval(interval);
                resolve();
            }

        }, 100);
    });
}

看起来您需要在函数
准备就绪
中使用
变量
值进行解析,如下所示:

resolve(variable);
然后在控制台日志中添加一个参数以确定更多信息,如下所示:

fetchSecondValueFromServer() {
    is_ready(this.value).then((returnValue) => {
        console.log("there", returnValue);       
    }); 
}

算了吧,
中的值已准备就绪
通过值传递!Javascript需要实现&因此我们可以通过ref传递垃圾

问题在于
is\u ready
功能的逻辑。看起来您希望该函数反复检查该值是否存在,然后在该值存在时进行解析。然而,由于JS中闭包的工作方式,即使在
这个.value
改变之后,
变量
参数在该函数体的上下文中也只有一个值。看看这个小例子:

let secret='尚未找到'
函数checkSecret(secretArg){
设置间隔(()=>{
console.log(secretArg)
}, 500)
}
checkSecret(秘密)

setTimeout(()=>{secret='secret found!'},1000)
如果您建议我们必须传递一个参数来解析,那不是我尝试过的。是的,谢谢,我找到了。我希望将来我们可以通过参考。有人不喜欢我的通过参考评论