【问题标题】:React Native unhandled promise rejection network errorReact Native 未处理的承诺拒绝网络错误
【发布时间】:2020-07-05 07:06: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);

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

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

【问题讨论】:

    标签: react-native


    【解决方案1】:

    这是因为您没有使用.catch,而是使用.then.then 用于 promise 成功 reloved 时,.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
    
    

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2021-06-25
      • 2016-12-15
      • 2018-02-09
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多