react-native - 如何在函数外部使用变量来反应本机?
问题描述
我需要在这个函数之外使用那个变量“让结果”。我需要在另一个函数中使用该变量。我怎么才能得到它?我的代码如下所示:
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Authorization': 'Bearer ' + this.state.clientToken,
},
})
.then((response) => response.json())
.then((responseJson) => {
let result= JSON.parse((responseJson.lstsurveyoncode))
let answer = JSON.parse(responseJson.lstsurveyoncode)[0].qoptions
console.log("responsejson",result[1].QUESTIONCODE)
console.log("answerrr",answer);
console.log("data length",result.length);
this.setState({
isLoading:false,
dataresponse:result,
// count:Object.keys(dataresponse).length
},function(){
});
解决方案
你应该阅读 react-native 中的异步等待和状态管理。async
为了快速解决,您应该使用修饰符和await
结果标记您的函数。下面的示例代码:
async function yourRequest() {
return new Promise((resolver, rejected) => {
// your async request
})
.then(response => response.json())
.then(responseJson => {
const result = JSON.parse(responseJson.lstsurveyoncode)
const answer = JSON.parse(responseJson.lstsurveyoncode)[0].qoptions
// ...
return {
result: result,
answer: answer,
}
})
}
async function handleResponse() {
const response = await yourRequest()
// and now, you can access to variables declared at `makeRequest` function
console.log(response.result)
console.log(response.answer)
}
推荐阅读
- powershell - 哈希表数组的格式表
- python - Python 验证 CSV 数据
- arrays - 组合来自两个不同 API 的数据并解析响应(节点打字稿)
- specflow - 嗨,我正在使用 Specflow 和 extentReport。如何将待处理步骤打印到我的范围报告?
- javascript - Angular 应用程序的文本到语音 - “allowJs 未设置”问题
- php - 如何在循环中重复显示数据
- xml - 自动生成 XSLT - 通用/默认 XSLT
- c++ - 使用静态 qmake 使用 QT Widget 插件
- mysql - 如何获得一个 SQL 查询来组合两个表
- angular - 具有特殊字符的映射模型的 Mat-Table matCellDef 问题