React.js搜索功能优化:实现搜索名称时同时返回并展示ID
Got it, let's get your search results displaying both the doctor's name and their ID! The core problem right now is that you're only storing the firstname string in your suggestions array—you need to keep track of the full object that includes both id and firstname instead. Here's how to adjust your code step by step:
Step 1: Store Full Objects in Suggestions
Instead of pushing just the firstname into the suggestions array, push an object that holds both the id and name:
// Replace your existing suggestions setup with this const suggestions = []; showSerch.forEach(function (data) { suggestions.push({ id: data.id, name: data.firstname }); // Store both id and name });
Step 2: Update Filter Logic for Object Properties
Your onChange function was filtering strings—now it needs to check the name property of each suggestion object:
const onChange = (event) => { const value = event.target.value; setInputValue(value); setShowResults(false); // Filter based on the name property of the suggestion object const filteredSuggestions = suggestions.filter((suggestion) => suggestion.name.toString().toLowerCase().includes(value.toLowerCase()) ); setFilteredSuggestions(filteredSuggestions); setDisplaySuggestions(true); };
Step 3: Render Both Name and ID in Results
Modify the SuggestionsList component to display both the name and ID in each list item (I also fixed the onClick handler that was firing immediately):
const SuggestionsList = (props) => { const { suggestions, inputValue, onSelectSuggestion, displaySuggestions, selectedSuggestion, } = props; if (inputValue && displaySuggestions) { if (suggestions.length > 0) { return ( <ul className="suggestions-list" style={styles.ulstyle}> {suggestions.map((suggestion, index) => { const isSelected = selectedSuggestion === index; const classname = `suggestion ${isSelected ? "selected" : ""}`; return ( <li style={styles.listyle} key={index} className={classname} onClick={() => onSelectSuggestion(index)} > {suggestion.name} (ID: {suggestion.id}) {/* Show both name and ID */} </li> ); })} </ul> ); } else { return <div>No suggestions available...</div>; } } return <></>; };
Step 4: Track Selected ID (Optional but Useful)
If you want to use the selected ID for later actions (like API calls), add a state to store it and update it when a suggestion is clicked:
// Add this state at the top of your component const [selectedDoctorId, setSelectedDoctorId] = React.useState(""); // Update onSelectSuggestion to save the ID const onSelectSuggestion = (index) => { setSelectedSuggestion(index); setInputValue(filteredSuggestions[index].name); // Set input to the name setSelectedDoctorId(filteredSuggestions[index].id); // Save the selected ID setFilteredSuggestions([]); setDisplaySuggestions(false); };
Full Modified Code
Here's the complete component with all changes applied:
import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import { useState, useEffect } from "react"; import axios from "axios"; const initialState = { idaddProducts: "", }; const Searchclients = () => { const [showResults, setShowResults] = React.useState(true); const [poName, pnName] = React.useState(initialState); const [showSerch, setShowSerch] = React.useState([]); const [inputValue, setInputValue] = React.useState(""); const [filteredSuggestions, setFilteredSuggestions] = React.useState([]); const [selectedSuggestion, setSelectedSuggestion] = React.useState(0); const [displaySuggestions, setDisplaySuggestions] = React.useState(false); const [selectedDoctorId, setSelectedDoctorId] = React.useState(""); // New state for selected ID // Store full objects with id and name const suggestions = []; showSerch.forEach(function (data) { suggestions.push({ id: data.id, name: data.firstname }); }); const onChange = (event) => { const value = event.target.value; setInputValue(value); setShowResults(false); const filteredSuggestions = suggestions.filter((suggestion) => suggestion.name.toString().toLowerCase().includes(value.toLowerCase()) ); setFilteredSuggestions(filteredSuggestions); setDisplaySuggestions(true); }; const onSelectSuggestion = (index) => { setSelectedSuggestion(index); setInputValue(filteredSuggestions[index].name); setSelectedDoctorId(filteredSuggestions[index].id); // Save selected ID setFilteredSuggestions([]); setDisplaySuggestions(false); }; const SuggestionsList = (props) => { const { suggestions, inputValue, onSelectSuggestion, displaySuggestions, selectedSuggestion, } = props; if (inputValue && displaySuggestions) { if (suggestions.length > 0) { return ( <ul className="suggestions-list" style={styles.ulstyle}> {suggestions.map((suggestion, index) => { const isSelected = selectedSuggestion === index; const classname = `suggestion ${isSelected ? "selected" : ""}`; return ( <li style={styles.listyle} key={index} className={classname} onClick={() => onSelectSuggestion(index)} > {suggestion.name} (ID: {suggestion.id}) </li> ); })} </ul> ); } else { return <div>No suggestions available...</div>; } } return <></>; }; useEffect(() => { axios .get("my-url") .then((res) => { const data = res.data; setShowSerch(data); }); }, []); // Optional: Log selected ID to test console.log("Selected Doctor ID:", selectedDoctorId); return ( <div className="note-container" style={styles.card}> <div style={styles.inner}> <p style={{ textAlign: "left" }}>Search Doctors</p> <form className="search-form" style={{}}> {showResults ? ( <FontAwesomeIcon style={{ marginRight: "-23px" }} icon={faSearch} /> ) : null} <input onChange={onChange} value={inputValue} style={styles.input} type="Search" /> <SuggestionsList inputValue={inputValue} selectedSuggestion={selectedSuggestion} onSelectSuggestion={onSelectSuggestion} displaySuggestions={displaySuggestions} suggestions={filteredSuggestions} /> </form> </div> </div> ); }; // Define your styles here (you likely have this already) const styles = { card: {}, inner: {}, ulstyle: {}, listyle: {}, input: {} }; export default Searchclients;
Now your search results will show both the doctor's name and their corresponding ID, and you'll have access to the selected ID via the selectedDoctorId state if you need it for further actions.
内容的提问来源于stack exchange,提问作者vivek kn

