【问题标题】:fetch data error with react native使用本机反应获取数据错误
【发布时间】:2018-07-31 21:06:57
【问题描述】:

我使用了两个类 我称第二类如下

let s = new SearchExtend();

output = s.fetchData(search)
alert(output)

第二个功能:

fetchData = (search) => {

      fetch('http://example.com/search.php' , {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({

          // Getting the search.
          search: search
        })
      }).then((response) => response.json())

       .then((responseJson) => {
             return responseJson;
       })
       .catch((error) => {
         console.error(error);
       });
}

但我进入“警报”未定义

当我使用 this.setState 而不是 return 时,出现以下错误:

警告 setstate(...) 只能更新挂载或挂载的组件

【问题讨论】:

  • 让 form = new FormData(); s.fetchData(form ) 使用 FormData 并通过附加的形式传递参数和值 form.append("paramname", 'paramvalue') body:search no need JSON.stringify

标签: javascript reactjs react-native react-redux


【解决方案1】:

你得到undefined,因为你正在使用promise。最初它返回 undefined ,一旦 promise 被解决,你就会得到实际的数据。

处理此问题的更好方法是返回承诺并在外部解决它,如下所示:-

const fetchApi = () => {
   return fetch("https://swapi.co/api/people" , {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
  }).then((response) => {
    return response.json();
  })
   .then((responseJson) => {
    return responseJson;
  })
    .catch((error) => {
    console.error(JSON.stringify(error));
  });
}


fetchApi()
.then((data) => {
  console.log("data", data);
})

【讨论】:

  • 他变得不确定,因为他在fetchData 方法中没有返回任何内容。它与 Promises 无关。
  • 感谢它的工作,如何在加载数据之前打印文本,例如加载...或导入类
猜你喜欢
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多