reactjs - 反应将数据从输入传递到异步函数
问题描述
所以,我试图将数据从输入元素传递到我的 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;
解决方案
有两个问题:
要获取输入值,请使用受控组件:将输入值放入状态并添加更改处理程序。
要设置
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>
);
}
}
推荐阅读
- android - 禁用 EditText 剪贴板的编辑/文本输入和粘贴
- c# - 使用 ExecuteNonQuery 时 Parallel.Foreach 死锁?
- python - 'requests' 抓取 URL 返回 404 即使有标题和页面肯定存在
- database - Word press 表单数据提交到另一个数据库
- windows - Windows 区分大小写
- sql - 按 ID 分组以查看订单状态
- python - else 部分没有被执行,每次打印“user1 和 user2 相等”,即使它们不是
- python - 如何在 microsoft windows 10 中使用 pyenv/pyenv-win 安装 python 版本?
- python - 如何确定python中csv文件中列的数据类型?
- c++ - 如何将 ifstream 和 ofstream 传递给 C++ 中的相同函数对象?