React将数据从Input传递到Async函数



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

目前我只是在callAPI中有一个虚拟/占位符ipaddress,以测试按钮是否工作并调用函数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>
);
}
}

您可以将输入字段的值存储在state中,并直接在async调用中使用它。

另外,你需要一个onchange处理程序,因为每次你更新输入文本时,state应该知道更新的值。

import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
// HERE.........................
this.state = { apiResponse: '', text : null };
}

// HERE ...........................
handleChnage = (e) => this.setState({text : e.target.value})
async callAPI() {
// Checking the input value and pass to api..................
console.log(this.state.text)
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);
// Don't use it..............use state to pass the data
document.getElementById('city').textContent = json.city;
document.getElementById('state').textContent = json.region_code;
document.getElementById('zip').textContent = json.zip;
}
render() {
// Here on Input element .................
return (
<div className="App">
<h1>IP Search</h1>
<input type="text" value={this.state.text} onChange={this.handleChange}></input>
<button onClick={this.callAPI}>Search IP</button>
<p>
<span id="city" /> <span id="state" /> <span id="zip" />
</p>
</div>
);
}
}
export default App;

注意-不要在React中使用getElementById等命令式方法。

请避免在Reactjs中使用DOM方法,这里有一个你可能想对你的应用程序做的例子。'

import React,{useState} from 'react';

function App(){
const [apiRes,setApiRes]= useState('');
const [loading,setLoadng]= useState(false);
const callAPI= async()=>{
// supose this is your api response in json
const hello={
city:"city1",
region_code:"region#123",
zip:"00000"
}
// loading while city and zip are not available
setLoadng(true)
await setTimeout(()=>{setApiRes(hello)},5000)

}
return (
<div className="App">
<h1>IP Search</h1>
<input type="text"></input>
<button onClick={callAPI}>Search IP</button>
{!apiRes && loading && <p>loading count till 5...</p>}
<p>
{apiRes &&
(
<>
<span> {apiRes.city}</span>
<span> {apiRes.region_code}</span>
<span> {apiRes.zip}</span>
</>
)}
</p>
</div>
);
}

export default App;

'链接到sandbox: [sandbox]: https://codesandbox.io/s/priceless-mclaren-y7d7f?file=/src/App.js/"点击这里运行上面的代码">

最新更新