我需要从执行获取调用的 react native 中的另一个页面返回函数的结果。我使用的方法如下。据我所知,这是因为异步调用。有没有一种特殊的方法可以在本机反应中实现这一点?
fetchcall.js
import address from '../actions/address'
const dashboard = {
getvals(){
return fetch(address.dashboardStats(),
{method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( {...
}),
})
.then((response) => response.json())
.then((responseData) => {
console.warn(responseData);
return responseData;
})
.catch((error) => { console.warn(error); })
.done();
// return 'test_val'';
}
}
export default dashboard;
仪表板.js
import dashboard from '../../services/dashboard';
class Dashboard extends Component {
componentDidMount(){
console.warn(dashboard.getvals());
}
}
export default connect(mapStateToProps, bindAction)(Dashboard);
它将结果显示为“未定义”,但 fetch 调用有效并显示结果。有什么建议吗?
原文由 Dinith Minura 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 fetchcall.js 中,您将返回一个 Promise。此外,由于您在
.then()
方法本身中返回responseData
,因此您不需要.done()
方法。由于
getvals()
正在返回一个 Promise,您需要在.then()
方法中访问它的值。总的来说,你的代码应该是这样的: