从函数返回json数据

从函数返回json数据,json,reactjs,react-native,Json,Reactjs,React Native,我使用一个函数获取以下代码: var URL='...' export function PostData(method,data){ fetch(URL+method,{ method:'POST', body:JSON.stringify(data), headers:{'Content-Type':'application/json'}, }).then(res => res.json()) .then(re

我使用一个函数获取以下代码:

var URL='...'

export function PostData(method,data){
    fetch(URL+method,{
        method:'POST',
        body:JSON.stringify(data),
        headers:{'Content-Type':'application/json'},

    }).then(res => res.json())
    .then(response => {
        var ret=JSON.stringify(response)
        return ret
    })
    .catch((error) => {
        console.error(error)
    })
}
并按如下方式使用:

var retData=PostData('login/Authenticate',data)

retData为空,但在函数ret中有数据

PostData
函数当前不返回任何内容,因此它为空。 第一步是添加
return
语句:

export function PostData(method,data){
  return fetch(URL+method,{
    method:'POST',
    ...
这将使您的函数返回一个值,但不仅仅是一个简单的值,而是一个承诺!承诺不是最容易理解的,但也有很多人试图解释它们
-
-

现在,您如何使用该值呢

PostData('login/Authenticate',data)
.then(retData => {
  // ... use retData here
});
现在,您使用了react native标记,因此我假设您希望在
render
函数中使用此值。您不能简单地通过将
PostData
调用放入
render
函数来实现这一点。您必须将其置于状态,然后在
render
中使用该值:

state = { retData: null }

componentDidMount() {
  PostData('login/Authenticate',data)
  .then(retData => {
    // This puts the data in the state after the request is done
    this.setState({ retData: retData });
  });
}

render() {
  let retData = this.state.retData;
  // ... use retData in your render here, will be `null` by default

有很多不同或更简洁的方法可以做到这一点,但我试图让这个答案尽可能简单明了:)

此时它是空的,因为对
fetch
的调用是异步的,在它移动到下一个语句时,文本被设置为
undefined
,因为它还没有被解析。一种解决方法是返回promise对象本身,然后使用
.then
在解析后获得响应

var URL='…'
导出函数PostData(方法、数据){
//返回承诺对象
返回获取(URL+方法{
方法:“POST”,
正文:JSON.stringify(数据),
标题:{
“内容类型”:“应用程序/json”
},
}).then(res=>res.json())
。然后(响应=>{
var ret=JSON.stringify(响应)
回程网
})
.catch((错误)=>{
控制台错误(错误)
})
}
PostData('login/Authenticate',data)。然后(response=>{
//对回应做点什么

});
谢谢,我可以使用retData['Message']访问json的项为什么?请记住,第一次运行(在PostData“完成”之前),retData将为
null
。您可以在呈现函数中设置一个检查项,如
如果(retData==null){return Loading;}
谢谢,我可以使用retData['Message']访问json的项为什么?这是因为
retData
是一个包含键的对象
Message
对不起,我不能使用retData['Message']访问它