首页 > 解决方案 > 未处理的承诺拒绝:TypeError:网络请求在博览会中失败

问题描述

我正在尝试使用我的 api,这是代码

在这里,我创建了家庭课程和状态

 export default class  Home extends React.Component {
   state = {
     region: null,
     places: []
   }

在这里我连接到我的 api 并尝试搜索这些地方

   async componentDidMount() {
     fetch('http://localhost:3000/auth/list')
       .then(res => res.json())
       .then(res =>{
         this.setState({
           places: res
      
         })
       })

在这里,我将它呈现在地图中

 render() {
     const {region} = this.state;
     return (
       <View style={styles.Container}>
         <MapView style={styles.Mapview} 
         region={region}
         showsUserLocation={true}
         zoomEnabled={true}
         showsPointsOfInterest={false}
         initialRegion={region}
       
         >

在这里我创建一个标记

           {this.state.places.map(places => (
             <MapView.Marker
             key={places.id}
             title={places.title}
             description={places.description}
             coordinate={{
               latitude: places.latitude,
               longitude: places.longitude
             }}
        
             />
           ))}
         </MapView>

但它说:未处理的承诺拒绝:TypeError:网络请求失败

标签: react-nativeapi

解决方案


这将抛出一个应该使用 catch 函数捕获的错误。试试这个方法

return fetch(url)
  .then(function (response) {
    return response.json();
  })
  .then(function (res) {
    this.setState({
      places: res,
    });
  })
  .catch(function (error) {
    console.log("Error");
    // ADD THIS THROW error
    throw error;
  });

推荐阅读