【问题标题】:Getting "Unreachable code no-unreachable" in ReactJS在 ReactJS 中获取“无法访问的代码”
【发布时间】:2018-06-02 13:30:33
【问题描述】:

我是在 React 中创建 GET 请求的新手。当有人在输入字段中输入 url 时,我正在尝试从 Instagram 内容中获取 media_id。有趣的是,我确实在 Inspector 中获得了以下 GET 请求的响应,但我不确定如何正确执行此操作。

以下是我的组件代码。

import React, { Component } from 'react';


export default class UrlInput extends Component {

  constructor(props){
    super(props);

    this.state = {
      term: '',
      mediaid: ''
    };
    this.onInputChange = this.onInputChange.bind(this);
  }
  componentDidMount(){
    const url = 'https://api.instagram.com/oembed/?url=http://instagram.com/p/Y7GF-5vftL/';
    fetch(url).then(response => {
        if(response.ok){
          return response.json();
        }
        throw new Error('Request failed!');
      },
      networkError => console.log(networkError.message)).then(jsonResponse => {
        return jsonResponse;
        console.log(jsonResponse);
      });
    }

  render(){
    return (
      <div className='search-bar'>
          <input
            value= {this.state.term}
            onChange={ event => this.onInputChange(event.target.value)} />

          <div>{this.state.term}</div>
      </div>
    );
  }
  onInputChange(term){
    this.setState({term});
  }
}

【问题讨论】:

  • 你能发布 GET 调用的响应吗?如果您在then 中添加debugger;,您应该能够单步执行处理浏览器响应的代码。

标签: ajax reactjs get state


【解决方案1】:

no-unreachable 只是一个警告,告诉您您的代码中有无法访问的代码。在这种情况下,它是console.log(jsonResponse) 之后的return jsonResponse

这是无法访问的,因为当代码找到 return 语句时,它只会跳出函数而不再继续,因此永远不会调用 console.log(jsonResponse)

【讨论】:

  • 这样做有不好的后果吗?
【解决方案2】:

去掉返回值后面的console.log()

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多