Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.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 如何在react native中从函数返回数据_Javascript_Reactjs_React Native_Function - Fatal编程技术网

Javascript 如何在react native中从函数返回数据

Javascript 如何在react native中从函数返回数据,javascript,reactjs,react-native,function,Javascript,Reactjs,React Native,Function,我试图从函数返回数据,但没有得到正确的数据 export const getApi = (url) => { return fetch(url) .then((response) => response.json()) .then((json) => { console.log(json); }) } 这是我的回答 我在这里叫它 componentDidMount(){ const dat

我试图从函数返回数据,但没有得到正确的数据

export const getApi = (url) => {
    return fetch(url)
        .then((response) => response.json())
        .then((json) => {
            console.log(json);
        })
}
这是我的回答

我在这里叫它

 componentDidMount(){
   const data= getApi(banner)       
   console.log('data',data)       
}

不确定您正试图在grand scheme中实现什么,但根据代码片段,您需要这样做:

export const getApi = (url) => {
   return fetch(url)
          .then((response) => response.json())
          .then(json => json)

}
然后像这样使用它:

componentDidMount(){
   getApi(banner).then(data => console.log("data", data))   
}

你可以把你的函数重写成这个。它也更具可读性

export const getApi = async (url) => {
   const response = await fetch(url);
   const json = await response.json();
   console.log(json);
   return json;
}

我想你应该学习一下promises和javascripts异步natur的概念谢谢,我现在修好了problem@AlokSingh不客气。如果答案能解决你的问题,别忘了接受。
export const getApi = async (url) => {
   const response = await fetch(url);
   const json = await response.json();
   console.log(json);
   return json;
}