node.js - 是否可以将自动搜索字段从硬编码 'suggestions' 更改为数据库中的数据?

标签 node.js reactjs database mongodb express

我找到了硬编码数据自动填充搜索字段的完整代码。它表现得很好,直到我意识到我必须将我的数据库连接到它。我正处于 MERN 项目(有史以来第一个)的末尾,我不知道如何传递存储在数据库中的数据(我只想在这里传递名字和第二个名字)。

import AutocompleteFunc from './AutocompleteFunc';

  export default class Autocomplete extends Component {
   render() {
    return (
        <div style = {{position: "relative", top: "-60px", fontSize: '16px', right: "0px", width: 
    "150px", zIndex: 1}}>
       <AutocompleteFunc
    suggestions={[
  "Dawid",
  "Test Employee",
    ]}
  />
</div>
    )
  }
}

以及它的功能:

 import React, { Component, Fragment } from "react";
 import PropTypes from "prop-types";
 import './AutocompleteFunccss.css'

 class AutocompleteFunc extends Component {
          static propTypes = {
            suggestions: PropTypes.instanceOf(Array)
          };

          static defaultProps = {
            suggestions: []
          };

          constructor(props) {
            super(props);

            this.state = {
              // The active selection's index
              activeSuggestion: 0,
              // The suggestions that match the user's input
              filteredSuggestions: [],
              // Whether or not the suggestion list is shown
              showSuggestions: false,
              // What the user has entered
              userInput: ""
            };
          }

          // Event fired when the input value is changed
          onChange = e => {
            const { suggestions } = this.props;
            const userInput = e.currentTarget.value;

            // Filter our suggestions that don't contain the user's input
            const filteredSuggestions = suggestions.filter(
              suggestion =>
                suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
            );

            // Update the user input and filtered suggestions, reset the active
            // suggestion and make sure the suggestions are shown
            this.setState({
              activeSuggestion: 0,
              filteredSuggestions,
              showSuggestions: true,
              userInput: e.currentTarget.value
            });
          };

          // Event fired when the user clicks on a suggestion
          onClick = e => {
            // Update the user input and reset the rest of the state
            this.setState({
              activeSuggestion: 0,
              filteredSuggestions: [],
              showSuggestions: false,
              userInput: e.currentTarget.innerText
            });
          };

          // Event fired when the user presses a key down
          onKeyDown = e => {
            const { activeSuggestion, filteredSuggestions } = this.state;

            // User pressed the enter key, update the input and close the
            // suggestions
            if (e.keyCode === 13) {
              this.setState({
                activeSuggestion: 0,
                showSuggestions: false,
                userInput: filteredSuggestions[activeSuggestion]
              });
            }
            // User pressed the up arrow, decrement the index
            else if (e.keyCode === 38) {
              if (activeSuggestion === 0) {
                return;
              }

              this.setState({ activeSuggestion: activeSuggestion - 1 });
            }
            // User pressed the down arrow, increment the index
            else if (e.keyCode === 40) {
              if (activeSuggestion - 1 === filteredSuggestions.length) {
                return;
              }

              this.setState({ activeSuggestion: activeSuggestion + 1 });
            }
          };

          render() {
            const {
              onChange,
              onClick,
              onKeyDown,
              state: {
                activeSuggestion,
                filteredSuggestions,
                showSuggestions,
                userInput
              }
            } = this;

            let suggestionsListComponent;

            if (showSuggestions && userInput) {
              if (filteredSuggestions.length) {
                suggestionsListComponent = (
                  <ul class="suggestions">
                    {filteredSuggestions.map((suggestion, index) => {
                      let className;

                      // Flag the active suggestion with a class
                      if (index === activeSuggestion) {
                        className = "suggestion-active";
                      }

                      return (
                        <li
                          className={className}
                          key={suggestion}
                          onClick={onClick}
                        >
                          {suggestion}
                        </li>
                      );
                    })}
                  </ul>
                );
              } else {
                suggestionsListComponent = (
                  <div class="no-suggestions">
                    <em>No suggestions, you're on your own!</em>
                  </div>
                );
              }
            }

            return (
              <Fragment>
                <input
                  type="text"
                  onChange={onChange}
                  onKeyDown={onKeyDown}
                  value={userInput}
                />
                {suggestionsListComponent}
              </Fragment>
            );
          }
        }

        export default AutocompleteFunc;

最佳答案

您可以创建Api来提供suggestions源数据并在 <AutocompleteFunc suggestions={**names from api**} /> 中使用它
当然,对于许多名字来说这不是一个好的解决方案

检查这个sample

关于node.js - 是否可以将自动搜索字段从硬编码 'suggestions' 更改为数据库中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734792/

相关文章:

mysql - 如何将 BGL 转换为 MySQL 表?

C# Oracle 表问题

node.js - 使用 Cloud Functions REST API 请求将文件存储在 Firebase Storage 中

javascript - reactRouter2.default 使用 Babel 未定义

reactjs - 类型 'Readonly<{}>' 上不存在“ValueChanging”

reactjs - 有没有办法获取存储在 api slice [RTK Query] 中的所有响应?

mysql - 如何将多个表连接并分组连接到一个查询中

node.js - Bot Framework Node.js 发送给特定用户的临时消息

node.js - 从 Mongoose 模型中找到的 native 驱动程序不返回光标

reactjs - 如何在react redux中仅选择映射数据上的一个复选框