在 ReactJS 中获取“无法访问的代码 no-unreachable”

Ish*_*tel 4 ajax state get reactjs

我是在 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});
  }
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*yef 8

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

它是不可达的,因为当代码找到一个 return 语句时,它会跳出函数,不再继续下去,因此console.log(jsonResponse)永远不会被调用。


小智 5

我遇到了同样的问题。似乎是因为 return 的括号应该是 inline likereturn ( 和 not like

return

(

这为我解决了问题