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;
}