【问题标题】:react fetch data and render the error if any反应获取数据并呈现错误(如果有)
【发布时间】:2018-12-10 17:37:54
【问题描述】:

我已经实现了这个组件来获取一些字符信息。我想知道名字,车辆和星际飞船。如果由于某种原因字符无法加载,我想显示特定的错误消息。 在下面的代码中,为了查看错误是否被捕获(确实如此),url 被破坏。

这是我的代码。

   class Character extends Component {
      constructor(props) {
        super(props);
         this.state = {
          name: '',
          vehicles: [],
          starships: [],
        }
        this.handleCharacter();
      }

      handleCharacter(){
        let vehicles = [];
        let starships = [];
        let name= '';
        fetch('https://swapi.co/api/people/jhjh').then(results => {
          if(results.ok){
            return results.json();
          }
          throw new Error('Character fail to load');
        })
        .then(data => {
          data.results.forEach(item => {
            name = item.name;
            vehicles.push(item.vehicles);
            starships.push(item.starships);
          });
          this.setState(() => {
              return{ 
                  name: name,
                  vehicles:vehicles,
                  starships:starships
              }
          })
        })
        .catch(function(error) {
            console.log(error.message)
        });
      }

      render(){
        return (
          <div>
           //a bunch of code rendered
          // Somewhere here I wand to render a div only if there is an error
         </div>
        );
      }
    }

【问题讨论】:

    标签: reactjs error-handling fetch


    【解决方案1】:

    您需要通过catch 方法设置状态。但是您需要使用箭头函数,以便this 引用该组件。

     .catch(error => {
        this.setState({ error: error.message } )
      });
    

    然后在你的渲染中你可以检查this.state.error

    确保在成功后再次清除它

    this.setState(() => {
              return{ 
                  name: name,
                  vehicles:vehicles,
                  starships:starships,
                  error: false
              }
          })
    

    【讨论】:

    • 除了使用状态还有其他方法吗?
    【解决方案2】:

    你在正确的轨道上,你可以做的只是通过在你的 catch 语句中设置状态来有条件地呈现错误消息:

     .catch(function(error) {
        this.setState({ error: error.message } )
      });
    
    render(){
        return (
          <div>
           //a bunch of code rendered
          {this.state.error && <div>{this.state.error}</div>}
         </div>
        );
      }
    

    【讨论】:

    • 这是我的第一个想法,但我收到错误 TypeError: Cannot read property 'setState' of undefined.
    猜你喜欢
    • 2021-08-07
    • 2022-01-23
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多