首页 > 解决方案 > 反应将数据从输入传递到异步函数

问题描述

所以,我试图将数据从输入元素传递到我的 React App.js 文件中的异步函数中。我无法理解如何将输入值推送到 callAPI 函数中。

目前,我在 callAPI 中只有一个虚拟/占位符 IP 地址,以便测试按钮是否正常工作并调用 onClick 函数。这是我的代码..

import React from 'react';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: '' };
  }

  async callAPI() {
    const ipaddress = '8.8.8.8';
    const api_url = `http://localhost:9000/ipdata/${ipaddress}`;
    const res = await fetch(api_url, {
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
    });
    const json = await res.json();
    console.log(json);
    document.getElementById('city').textContent = json.city;
    document.getElementById('state').textContent = json.region_code;
    document.getElementById('zip').textContent = json.zip;
  }

  render() {
    return (
      <div className="App">
        <h1>IP Search</h1>
        <input type="text"></input>
        <button onClick={this.callAPI}>Search IP</button>
        <p>
          <span id="city" /> <span id="state" /> <span id="zip" />
        </p>
      </div>
    );
  }
}

export default App;

标签: reactjs

解决方案


有两个问题:

  • 要获取输入值,请使用受控组件:将输入值放入状态并添加更改处理程序。

  • 要设置city, state,zip部分,不要使用普通的 DOM 方法(在 95% 的情况下,在 React 中应该避免这种方法)——而是将响应置于状态。

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { apiResponse: '', inputValue: '', result: {} };
    }

    async callAPI() {
        try {
            const api_url = `http://localhost:9000/ipdata/${this.state.inputValue}`;
            const res = await fetch(api_url, {
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                },
            });
            const result = await res.json();
            this.setState({ result });
        } catch (error) {
            // handle errors - don't forget this part
        }
    }

    render() {
        return (
            <div className="App">
                <h1>IP Search</h1>
                <input
                    type="text"
                    value={this.state.inputValue}
                    onChange={e => this.setState({ inputValue: e.target.value })}
                />
                <button onClick={this.callAPI}>Search IP</button>
                <p>
                    <span>{this.state.result.city}</span>
                    <span>{this.state.result.state}</span>
                    <span>{this.state.result.zip}</span>
                </p>
            </div>
        );
    }
}

推荐阅读