[英]React + Spring @GetMapping with @RequestParam simple app
我正在尝试制作一个简单的 web 应用程序,它将有 3 个 forms 用于数据输入、提交按钮和结果表单。
要求:当我在 forms 中输入数据并按下提交按钮时,这些参数应该是 go 到 controller,之后 React 还应该解析来自 controller 的 json 响应的数据,并在结果表单中显示解析的数据。
我有 Spring Controller 接受 3 个参数并返回 json 文件作为响应。
但我是 React 的新手。 我尝试过使用不同的方法,但坚持在这种情况下我需要用什么方式来做。 所以需要帮助来创建一个简单的 React 部分。
Controller部分:
@GetMapping("/current/city")
public JSONObject getCurrentPollutionDataByCityStateCountry(
@RequestParam(value = "city") String city,
@RequestParam(value = "state") String state,
@RequestParam(value = "country") String country
) {
try {
return pollutionService.getCurrentPollutionDataByCityStateCountry(city, state, country);
} catch (Exception e) {
e.printStackTrace();
}
return new JSONObject();
}
响应示例:
{"date":"Tue Dec 06 22:13:32 CET 2022","no2":"48.67","pm10":"9.51","pm2_5":"5.85"}
更新这是我的 App.js 部分:
import React, {Component} from 'react'
import './App.css'
import axios from 'axios'
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: 'New York',
province: 'New York',
country: 'US',
responseData: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
axios.get('http://localhost:8080/pollution/current/city?' +
'city=' + this.state.city +
'&state='+ this.state.province +
'&country=' + this.state.country)
//not sure about setState here and what is going after that
.then(response => this.setState({responseData: response.data.date}))
//need to take all fields from response
//just alert message with returned response for now
alert('Response: ' + this.state.responseData);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
City:
<input name="city" type="text" value={this.state.city} onChange={this.handleInputChange}/>
</label>
<br/>
<label>
State:
<input name="state" type="text" value={this.state.province} onChange={this.handleInputChange}/>
</label>
<br/>
<label>
Country:
<input name="country" type="text" value={this.state.country} onChange={this.handleInputChange} />
</label>
<br/>
<input type="submit" value="Submit"/>
</form>
);
}
}
export default App
但我不确定我的总体方法,尤其是我在 App.js 中留下评论的部分。
更准确地说,问题是:
我认为你需要解决的唯一问题是设置数据而不是 data.date 使用这个:
this.setState({responseData: response.data}))
然后使用访问您的数据字段
responseData.date
您可以用任何其他字段替换日期。
对警报做同样的事情。
你的代码工作正常,此外,你可以学习使用功能组件而不是 class,它更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.