React JS 访问 JSON 作为状态

React JS Accessing JSON as State

我完全是 React JS 的新手,我正在尝试创建一个应用程序,该应用程序将从 pokemon API 中获取 JSON 数据,然后我将使用这些数据在屏幕上显示。现在,我将其设置为用户必须输入他们正在寻找的宠物小精灵的名称,即皮卡丘,当按下搜索按钮时,应用程序将 API 调用 return JSON。过去几天我一直在寻找,但似乎找不到任何适合我目前设置代码的方法。如何将 JSON 输出绑定到一个组件,然后我才能向用户显示该组件?

这是js代码(App.js)

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
 constructor(props) {
    super(props);
    this.state = {value: ''};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  

   handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Text field value is: ' + this.state.value);

  fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')  
    .then(  
   function(response) {  
     if (response.status !== 200) {  
    console.log('Looks like there was a problem. Status Code: ' +  
      response.status);  
    return;  
     }
     // Examine the text in the response  
     response.json().then(function(data) {  
    console.log(data.name +" "+ data.id);  

     });  
   } 
    )  
    .catch(function(err) {  
   console.log('Fetch Error :-S', err);  
    });

    }


  render() {
   
   
   
    return (
    
    
    
      <div className="App">
      
      
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        
        <input type="text"
        placeholder="enter name of pokemon here"
        value={this.state.value}
        onChange={this.handleChange}
        />
        <button type="button" onClick={this.handleSubmit}>Search the Pokedex</button>
        
        
      </div>
      
      
      
    );
    
    
    
  }
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  </body>
</html>

问题截图: http://imgur.com/a/g9H5r

试试这个

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';
class App extends Component {
 constructor(props) {
    super(props);
    this.state = {
      value: '',
      data: {} //filled by fetch data from API
    };
  }
  

   handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Text field value is: ' + this.state.value);
     var _this = this;
  fetch('https://pokeapi.co/api/v2/pokemon/'+this.state.value+'/')  
    .then(  
   function(response) {  
     if (response.status !== 200) {  
    console.log('Looks like there was a problem. Status Code: ' +  
      response.status);  
    return;  
     }
     // Examine the text in the response  
     response.json().then(function(data) {  
    console.log(data.name +" "+ data.id);
                _this.setState({data: data});

     });  
   } 
    )  
    .catch(function(err) {  
   console.log('Fetch Error :-S', err);  
            _this.setState({data: {}});
    });

    }


  render() {
   
   var data = this.state.data;
   
    return (
    
    
    
      <div className="App">
      
      
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        
        <input type="text"
        placeholder="enter name of pokemon here"
        value={this.state.value}
        onChange={this.handleChange.bind(this)}
        />
        <button type="button" onClick={this.handleSubmit.bind(this)}>Search the Pokedex</button>
      <h3>{data.id}</h3>       
      <h3>{data.name}</h3>
        
      </div>
      
      
      
    );
   
  }
}

ReactDOM.render(App, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  </body>
</html>