【问题标题】:React JS Accessing JSON as StateReact JS 访问 JSON 作为状态
【发布时间】:2025-12-11 17:25:02
【问题描述】:

我对 React JS 完全陌生,我正在尝试创建一个应用程序,该应用程序将从 pokemon API 获取 JSON 数据,然后我将使用它在屏幕上显示。现在,我已经设置好了,用户必须输入他们正在寻找的口袋妖怪的名称,即皮卡丘,当按下搜索按钮时,应用程序将调用 API 以返回 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

【问题讨论】:

  • 将你得到的数据作为json保存在你的组件状态中
  • @JyothiBabuAraja 你能给我一个语法例子吗?
  • 试试下面的代码

标签: json reactjs react-jsx


【解决方案1】:

试试这个

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>

【讨论】:

  • 在调用类函数时不要忘记bind(this)
  • 我使用了您提供的代码,但似乎它仍然没有出现在“handleSubmit”函数中。我还有什么遗漏吗?
  • 现在使用更新的代码,是的,我将this 绑定到你的类函数
  • 我一定是做错了什么。我收到“这是未定义的”类型错误,不幸的是,输出仍然没有出现。我正在为我的问题添加屏幕截图,以便您查看。
  • 现在试试更新的。我用另一个局部变量更新了this