反应本机未处理的承诺拒绝网络错误

时间:2020-07-05 07:06:17

标签: react-native

我在React Native中使用此简单的api调用遇到问题,我也不知道为什么。我在reactJs上做了完全相同的事情,并且可以完美地在浏览器中工作。

const FlatListGames =({导航})=> {

 const [games,setGames] = useState([]);


 useEffect(() => {
    function fetchAPI(){
      axios.get('http://127.0.0.1:5000')
        .then(response => {
            setGames(response.data)
        })
        .then(error => console.log(error));
    }
    fetchAPI();
 }, [])

 console.log(games);

[未处理的承诺被拒绝:错误:网络错误]

  • node_modules / axios / lib / core / enhanceError.js:24:11 error.toJSON
  • dispatchXhrRequest中的
  • node_modules / axios / lib / adapters / xhr.js:114:23
  • Eventli.prototype.dispatchEvent中的
  • node_modules / event-target-shim / dist / event-target-shim.js:818:20
  • setReadyState中的
  • node_modules / react-native / Libraries / Network / XMLHttpRequest.js:575:10
  • __didCompleteResponse中的
  • node_modules / react-native / Libraries / Network / XMLHttpRequest.js:389:6
  • 发出
  • node_modules / react-native / Libraries / vendor / emitter / EventEmitter.js:189:10
  • __callFunction中的
  • node_modules / react-native / Libraries / BatchedBridge / MessageQueue.js:425:19
  • __guard $ argument_0中的
  • node_modules / react-native / Libraries / BatchedBridge / MessageQueue.js:112:6
  • __guard中的
  • node_modules / react-native / Libraries / BatchedBridge / MessageQueue.js:373:10
  • callFunctionReturnFlushedQueue中的
  • node_modules / react-native / Libraries / BatchedBridge / MessageQueue.js:111:4
  • [本地代码]:callFunctionReturnFlushedQueue中为空

1 个答案:

答案 0 :(得分:-1)

之所以发生这种情况,是因为您没有使用.catch,而是使用了.then.then用于成功撤销承诺时,.catch用于发生错误时,因此您需要用then替换第二个catch

const FlatListGames = ({ navigation }) => {

 const [games,setGames] = useState([]);


 useEffect(() => {
    function fetchAPI(){
      axios.get('http://127.0.0.1:5000')
        .then(response => {
            setGames(response.data)
        })
        .catch(error => console.log(error));
    }
    fetchAPI();
 }, [])

 console.log(games