You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API响应值存入React组件State?附代码求技术排查

Fixing Your React Joke Search Component

Let's work through the issues in your code step by step to get your API data properly stored in state and ready for rendering:

1. Fix the Controlled Input Binding

Your input is bound to this.state.title but your state only tracks term — this means your input won't sync with the state value correctly. Update the input's value prop:

<input 
  onChange={this.handleChange} 
  value={this.state.term} // Changed from this.state.title
  type="text" 
  name="term" 
  required 
  placeholder="cemetery" 
/>

2. Correct the State Update for API Results

The API returns response.data.results as an array already, but you're wrapping it in another array with [response.data.results]. This will make res a nested array, which will cause headaches when rendering. Fix the setState call:

.then(response => this.setState({ res: response.data.results })) // Removed the outer array brackets

3. Understand Async State Updates

setState is asynchronous — so when you console.log(this.state) right after calling it, you'll see the old state, not the updated one. If you need to log the updated state, use the setState callback:

axios.get(url, options)
  .then(response => {
    this.setState({ res: response.data.results }, () => {
      // This runs AFTER state is updated
      console.log(this.state);
    });
  })

4. Add Rendering for the Results

You mentioned wanting to render the data, so let's add a section to display the jokes in your render method:

render() {
  return (
    <div className="joke-container">
      <form className="jokes" onSubmit={this.handleSubmit}>
        <input 
          onChange={this.handleChange} 
          value={this.state.term} 
          type="text" 
          name="term" 
          required 
          placeholder="cemetery" 
        />
        <button type="submit" value="Search">Search</button>
      </form>
      {/* Render the results here */}
      <div className="joke-results">
        {this.state.res.length > 0 ? (
          this.state.res.map((joke, index) => (
            <div key={index} className="joke">
              <p>{joke.joke}</p>
            </div>
          ))
        ) : (
          <p>No jokes found yet — try searching for something!</p>
        )}
      </div>
    </div>
  );
}

Full Updated Component

Here's the complete fixed code:

import React, { Component } from 'react'
import axios from 'axios';

class New extends Component {
  state = { term: '', res: [] }

  handleChange = e => {
    this.setState({ term: e.target.value });
  };

  handleSubmit = e => {
    e.preventDefault();
    const url = `https://icanhazdadjoke.com/search?term=${this.state.term}`;
    const options = {
      method: 'GET',
      headers: { "Accept": "application/json" }
    };

    axios.get(url, options)
      .then(response => {
        this.setState({ res: response.data.results }, () => {
          console.log('Updated state:', this.state);
        });
      })
      .catch(error => {
        console.error('Error fetching jokes:', error.message);
      });
  };

  render() {
    return (
      <div className="joke-container">
        <form className="jokes" onSubmit={this.handleSubmit}>
          <input 
            onChange={this.handleChange} 
            value={this.state.term} 
            type="text" 
            name="term" 
            required 
            placeholder="cemetery" 
          />
          <button type="submit">Search</button>
        </form>
        <div className="joke-results">
          {this.state.res.length > 0 ? (
            this.state.res.map((joke, idx) => (
              <div key={idx} className="joke">
                <p>{joke.joke}</p>
              </div>
            ))
          ) : (
            <p>Search for a term to get dad jokes!</p>
          )}
        </div>
      </div>
    );
  }
}

export default New;

These changes should get your API data properly stored in state and rendered to the screen. The key issues were the mismatched input state binding, incorrect array wrapping in the state update, and missing result rendering.

内容的提问来源于stack exchange,提问作者Shivam_Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:52:44