简体   繁体   English

如何从 React 中的用户输入通过 ID 动态获取大学数据?

[英]How to get university data by ID dynamically from user input in React?

I have an API and I want whenever the user types a university name correctly, the API gets university info by ID dynamically.我有一个 API,我希望只要用户正确输入大学名称,API 就会通过 ID 动态获取大学信息。 I'm using get axios to get data, here's the UI image:我正在使用 get axios 来获取数据,这是 UI 图像:

在此处输入图像描述

And here's the code I wrote so far:这是我到目前为止编写的代码:


import React, { useState } from "react";
import { Container, Form, Button} from "react-bootstrap";
// Form, Button, Col, Row, Spinner
import axios from "axios"
import './styles.css';

function App() {

    const [institutionId, setInstitutionId] = useState("")

    const submitHandler = (e) => {
        e.preventDefault();
        let userData = {
            institutionId: institutionId
        };
        const APIKey = "API key is hidden";
        axios
            .get(`https://api.data.gov/ed/collegescorecard/v1/schools.json?id=${institutionId}&fields=school.name,2020.student.size&api_key=${APIKey}`, JSON.stringify(userData), {
                headers: {
                    "Content-Type": "application/json",
                },
            })
            .then((response) => {
                if (response.status === 200) {
                    console.log("successfully posted to the server!!");
                } else {
                    console.log("it wasn't successful");
                }
            })
            .catch((err) => {
                console.error(`Error: ${err}`);
            });
        console.log(JSON.stringify(userData));
        // setInstitutionId("");
    };

    return (
        <Container>
        <div className="App">
            <h1>University Finder App</h1>
        </div>
            <Form onSubmit={submitHandler}>
                <Form.Group className="mb-3" controlId="formBasicEmail">
                    <Form.Label>Type University Name</Form.Label>
                    <Form.Control type="text" value={institutionId}
                                  onChange={(e) => setInstitutionId(e.target.value)} />
                </Form.Group>
                <Button variant="primary" type="submit">
                    Submit
                </Button>
            </Form>
        </Container>
    );
}

export default App;

Thank you in advance for the help and let me know if I need to clarify my issue more.预先感谢您的帮助,如果我需要进一步澄清我的问题,请告诉我。

I'm not entirely sure if I follow your question and could use some clarification.我不完全确定我是否听懂了你的问题并且可以做一些澄清。 Your current code seems like it would fetch data from the API when the submit button is clicked since that query is executed within the submitHandler function.您当前的代码似乎会在单击提交按钮时从 API 获取数据,因为该查询是在submitHandler函数中执行的。 Are you instead trying to execute the query as soon as the user types in a valid university ID in the form (ie without clicking the submit button)?您是否尝试在用户在表单中输入有效的大学 ID 后立即执行查询(即不单击提交按钮)? Or is the issue with passing the university ID into the request itself?或者是将大学 ID 传递到请求本身的问题? Once you answer these I might be able to help out.一旦你回答了这些,我也许能帮上忙。

EDIT: Thanks for the clarification!编辑:感谢您的澄清! I would recommend first fetching the list of IDs mapped to their university names and storing that in some state (local state using useState is fine if you need to access this list only in this component).我建议首先获取映射到大学名称的 ID 列表并将其存储在某个状态(如果您只需要在此组件中访问此列表,则使用useState的本地状态很好)。 This could be a list like this:这可能是这样的列表:

[{ id: 1, label: 'Harvard University'}, { id: 2, label: 'Princeton' }]

This could be used to populate a dropdown and when user selects an option from the dropdown, the original API would be called using the id property of the option via the onSelect handler of the dropdown.这可用于填充下拉列表,当用户从下拉列表中选择一个选项时,将通过下拉列表的onSelect处理程序使用选项的 id 属性调用原始 API。 Hope this helps.希望这可以帮助。

Since the user don't know the Id for the university which he want to search, I suggest to fetch all the universities from that API and store it in a list then use a select component with autocomplete fill it with the list of universities and then the user will start to type the name of a university and he will get suggestions to select from.由于用户不知道他想搜索的大学的 Id,我建议从该 API 获取所有大学并将其存储在列表中,然后使用具有autocompleteselect组件填充大学列表,然后用户将开始输入大学名称,然后他将获得可供选择的建议。

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

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