简体   繁体   English

React + Spring @GetMapping 和@RequestParam 简单应用

[英]React + Spring @GetMapping with @RequestParam simple app

I am trying to make a simple web app, that will have 3 forms for data input, Submit button and Results form.我正在尝试制作一个简单的 web 应用程序,它将有 3 个 forms 用于数据输入、提交按钮和结果表单。

Requirements: When I enter a data in forms and push Submit button, these parameters should go to a controller and after that React should also parse data from json response that comes from the controller and show parsed data in the Results form.要求:当我在 forms 中输入数据并按下提交按钮时,这些参数应该是 go 到 controller,之后 React 还应该解析来自 controller 的 json 响应的数据,并在结果表单中显示解析的数据。

I have the Spring Controller that takes 3 parameters and return json file as a response.我有 Spring Controller 接受 3 个参数并返回 json 文件作为响应。

But I am new with React.但我是 React 的新手。 I've tried to use different approaches, but stuck with what way exactly I need to do it in this case.我尝试过使用不同的方法,但坚持在这种情况下我需要用什么方式来做。 So need a help to create a simple React part.所以需要帮助来创建一个简单的 React 部分。

Controller part: 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();
    }

Response example:响应示例:

{"date":"Tue Dec 06 22:13:32 CET 2022","no2":"48.67","pm10":"9.51","pm2_5":"5.85"}

UPDATE Here is my App.js part:更新这是我的 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

But I am not sure about my approach in general and particularly about parts where I left comments in App.js.但我不确定我的总体方法,尤其是我在 App.js 中留下评论的部分。

To be more precise with questions:更准确地说,问题是:

  1. Should this approach work for my case or I need to implement some different logic?这种方法应该适用于我的案例还是我需要实现一些不同的逻辑?
  2. If yes, how I can get all fields from response?如果是,我如何从响应中获取所有字段? I mean not only the first one (date) but no2, pm10, pm2_5 also.我的意思不仅是第一个(日期),还有 no2、pm10、pm2_5。 For now this logic can return only a first value from json.目前此逻辑只能返回 json 中的第一个值。
  3. How I can set these fields to show them in pop-up window (alert) or if question 2 will be solved, this thing also will be good in current form?我如何设置这些字段以在弹出窗口 window(警报)中显示它们,或者如果问题 2 将得到解决,这个东西在当前形式下也会很好吗?

The only problem I think you need to solve is to set the data not data.date use this:我认为你需要解决的唯一问题是设置数据而不是 data.date 使用这个:

this.setState({responseData: response.data})) 

then access your data fields using然后使用访问您的数据字段

responseData.date

you can replace date with any other field.您可以用任何其他字段替换日期。

do the same for alerts.对警报做同样的事情。

your code is working fine, furthermore, you can learn to use functional component instead of class, its much easier.你的代码工作正常,此外,你可以学习使用功能组件而不是 class,它更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM