React Native 未处理的承诺拒绝网络错误

2024-01-17

我在 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);

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

  • error.toJSON 中的 node_modules/axios/lib/core/enhanceError.js:24:11
  • dispatchXhrRequest 中的 node_modules/axios/lib/adapters/xhr.js:114:23
  • EventTarget.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
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 在 __guard$argument_0 中
  • __guard 中的 node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10
  • callFunctionReturnFlushedQueue 中的 node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4
  • [原生代码]:callFunctionReturnFlushedQueue中为null

发生这种情况是因为您没有使用.catch,而是你正在使用.then. .then用于成功解决承诺时,并且.catch用于发生错误时,因此需要替换第二个then with 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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native 未处理的承诺拒绝网络错误 的相关文章

随机推荐