Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将axios值返回到react js中的变量?_Javascript_Reactjs_Axios_Request Promise - Fatal编程技术网

Javascript 如何将axios值返回到react js中的变量?

Javascript 如何将axios值返回到react js中的变量?,javascript,reactjs,axios,request-promise,Javascript,Reactjs,Axios,Request Promise,我使用以下代码调用react render中的函数 {this.getChar({char})} 我有一个从axios返回值的函数 getChar(url){ var res = '' axios.get(url).then( datas => { res = datas.name console.log(datas.name) }); re

我使用以下代码调用react render中的函数

    {this.getChar({char})}
我有一个从axios返回值的函数

    getChar(url){
        var res = ''
        axios.get(url).then( datas => {
                res = datas.name
                console.log(datas.name)  
        });
        return res
    }
如果我运行getchar函数,在我的控制台中会显示我想要的字符串,但是如何将该字符串发送到'res'变量,以便我可以从getchar函数返回字符串

例如,如果我运行

    var url = 'https://some/url/'
我调用getchar函数

    getChar(url)
它将显示

    result

感谢您的帮助

这个问题几乎肯定会以重复的形式结束,因为这个问题的变体每天至少会被问一次。在res=datas.name的地方,使用类似于
this.setState({res:datas.name})
的东西。然后渲染
this.state.res
。在
返回之前在render函数内部调用此.getChar(),或者在其他适当的地方调用。首先,getChar函数中存在计时问题。它将在axios.get(…)完成之前很久返回res。其次,这个问题得到了很多回答:阅读JS中的
异步
编程和工作