首页 > 解决方案 > 如何在函数外部使用变量来反应本机?

问题描述

我需要在这个函数之外使用那个变量“让结果”。我需要在另一个函数中使用该变量。我怎么才能得到它?我的代码如下所示:

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-nativevariables

解决方案


你应该阅读 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)
}

推荐阅读