You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安装react-use-autosuggest包报错,请求排查解决方案

问题描述

我已经安装了react-use-autosuggest npm包,但运行时出现错误:'react-use-autosuggest@*' is not in this registry。尝试执行npm i --save @types/react-use-autosuggest时也出现相同错误:@types/react-use-autosuggest@*' is not in this registry。请问我遗漏了什么?

相关代码

导入语句

import { useContext, useState } from "react";
import { InputContext } from "../App";
import useAutoSuggest from "react-use-autosuggest";

package.json

{
  "name": "free-dictionary",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@grapecity/wijmo.react.all": "^5.20221.857",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/react-autosuggest": "^10.1.5",
    "autoprefixer": "^9.8.8",
    "axios": "^1.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.6.0",
    "react-scripts": "^5.0.1",
    "react-use-autosuggest": "^0.3.0",
    "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.2.17",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-preset-env": "^7.8.2",
    "postcss-pxtorem": "^5.1.1"
  },
  "peerDependencies": {
    "postcss": "^8.4.18"
  }
}

header.js

import { useContext, useState } from "react";
import { InputContext } from "../App";
import useAutoSuggest from "react-use-autosuggest";

const Header = () => {
  const [value, setValue] = useState("");
  const { inputValue, setInputValue } = useContext(InputContext);

  const handleInputChange = (e) => setValue(e.target.value);
  const handleSubmit = () => {
    setInputValue(value);
    setValue("");
  };

  const handleInputKeyDown = (e) => {
    if (e.key === "Enter") {
      setInputValue(value);
      setValue("");
      return;
    }
  };

  const suggestionList = useAutoSuggest(inputValue, handleInputChange);
  
  return (
    <div className="bg-gray-700">
      <div className="container mx auto py-8">
        <h1 className="text-3xl font-bold text-center text-white">
          My Free Dictionary
        </h1>
        <p className="text-center mt-1 mb-10 text-white text-lg">
          Find Definitions for word
        </p>

        <div className="flex itmes-center justify-center mt-5">
          <div className="flex border-2 border-gray-200 rounded">
            <input
              className="px-4 py-2 md:w-80"
              type="text"
              placeholder="Search.."
              onChange={handleInputChange}
              {...suggestionList}
              value={value}
              onKeyDown={handleInputKeyDown}
            />
            <button
              className="bg-blue-400 border-l px-4 py-2 text-white"
              onClick={handleSubmit}
            >
              Search
            </button>
          </div>
        </div>
        {inputValue && (
          <h3 className="text-gray-50 text-center mt-4">
            Results for:{" "}
            <span className="text-white font-bold">{inputValue}</span>
          </h3>
        )}
      </div>
    </div>
  );
};

export default Header;
问题原因与解决方案

核心问题

这个错误的根源是**react-use-autosuggest包已从npm公共仓库下架**,所以npm无法找到对应的包版本,它的@types类型包也从未存在过,自然也无法安装。你的package.json里虽然写了react-use-autosuggest": "^0.3.0",但这个版本现在在npm registry中已无记录,导致npm在安装或更新时找不到资源。

解决方案

你需要替换这个失效的包,改用其他维护活跃的React自动补全方案,以下是两种可行选择:

方案1:改用react-autosuggest

这是一个成熟且持续维护的自动补全组件,你已经安装了它的类型包@types/react-autosuggest,可以直接适配:

  1. 先卸载无效包:
npm uninstall react-use-autosuggest
  1. 安装react-autosuggest:
npm install react-autosuggest
  1. 修改Header.js适配组件逻辑(核心示例):
import Autosuggest from 'react-autosuggest';

// 替换成你的字典词库逻辑,比如从接口获取或本地定义
const wordList = ["apple", "banana", "cherry", "date"];

// 生成建议列表
const getSuggestions = (value) => {
  const inputVal = value.trim().toLowerCase();
  return wordList.filter(word => word.toLowerCase().includes(inputVal));
};

// 渲染单个建议项
const renderSuggestion = (suggestion) => <div>{suggestion}</div>;

const Header = () => {
  const [value, setValue] = useState("");
  const [suggestions, setSuggestions] = useState([]);
  const { inputValue, setInputValue } = useContext(InputContext);

  // 输入变化时更新值和建议
  const onChange = (event, { newValue }) => {
    setValue(newValue);
  };

  // 获取建议触发逻辑
  const onSuggestionsFetchRequested = ({ value }) => {
    setSuggestions(getSuggestions(value));
  };

  // 清空建议触发逻辑
  const onSuggestionsClearRequested = () => {
    setSuggestions([]);
  };

  // 输入框属性配置
  const inputProps = {
    placeholder: 'Search..',
    value,
    onChange,
    onKeyDown: (e) => {
      if (e.key === "Enter") {
        setInputValue(value);
        setValue("");
      }
    }
  };

  return (
    <div className="bg-gray-700">
      <div className="container mx auto py-8">
        {/* 原有标题、描述部分 */}
        <div className="flex items-center justify-center mt-5">
          <div className="flex border-2 border-gray-200 rounded">
            <Autosuggest
              suggestions={suggestions}
              onSuggestionsFetchRequested={onSuggestionsFetchRequested}
              onSuggestionsClearRequested={onSuggestionsClearRequested}
              getSuggestionValue={suggestion => suggestion}
              renderSuggestion={renderSuggestion}
              inputProps={inputProps}
              className="px-4 py-2 md:w-80"
            />
            <button
              className="bg-blue-400 border-l px-4 py-2 text-white"
              onClick={() => {
                setInputValue(value);
                setValue("");
              }}
            >
              Search
            </button>
          </div>
        </div>
        {/* 原有结果提示部分 */}
      </div>
    </div>
  );
};

方案2:使用React官方生态的useAutocomplete(React 18+)

如果你的项目使用React 18及以上版本,可以直接使用@react-aria/autocomplete提供的官方钩子,无需额外第三方组件:

  1. 卸载无效包:
npm uninstall react-use-autosuggest
  1. 安装依赖包:
npm install @react-aria/autocomplete @react-aria/listbox @react-stately/list
  1. 修改Header.js逻辑(核心示例):
import { useAutocomplete } from '@react-aria/autocomplete';
import { useListState } from '@react-stately/list';
import { useRef } from 'react';

const wordList = ["apple", "banana", "cherry", "date"];

const Header = () => {
  const inputRef = useRef(null);
  const [value, setValue] = useState("");
  const { inputValue, setInputValue } = useContext(InputContext);

  // 建议列表状态管理
  const listState = useListState({
    items: wordList.filter(word => word.toLowerCase().includes(value.trim().toLowerCase()))
  });

  const {
    inputProps,
    listBoxProps,
    getItemProps
  } = useAutocomplete({
    inputValue: value,
    onInputChange: (val) => setValue(val),
    onSelect: (item) => {
      setValue(item);
      setInputValue(item);
    },
    items: listState.items
  });

  return (
    <div className="bg-gray-700">
      <div className="container mx auto py-8">
        {/* 原有标题、描述部分 */}
        <div className="flex items-center justify-center mt-5 relative">
          <div className="flex border-2 border-gray-200 rounded">
            <input
              ref={inputRef}
              className="px-4 py-2 md:w-80"
              placeholder="Search.."
              {...inputProps}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  setInputValue(value);
                  setValue("");
                }
              }}
            />
            <button
              className="bg-blue-400 border-l px-4 py-2 text-white"
              onClick={() => {
                setInputValue(value);
                setValue("");
              }}
            >
              Search
            </button>
          </div>
          {/* 渲染建议列表 */}
          {listState.items.length > 0 && (
            <ul {...listBoxProps} className="absolute top-full left-1/2 transform -translate-x-1/2 bg-white border border-gray-200 rounded mt-1 w-80 max-h-60 overflow-y-auto">
              {listState.items.map((item, index) => (
                <li
                  key={item}
                  className={`px-4 py-2 cursor-pointer ${listState.selectedKey === item ? 'bg-gray-100' : ''}`}
                  {...getItemProps({item, index})}
                >
                  {item}
                </li>
              ))}
            </ul>
          )}
        </div>
        {/* 原有结果提示部分 */}
      </div>
    </div>
  );
};

额外注意事项

  • 务必从package.json中移除react-use-autosuggest相关依赖,避免后续npm操作持续报错。
  • 如果你之前是通过本地文件或私有源安装的react-use-autosuggest,也建议完全替换,因为该包已无官方维护,后续可能出现兼容性问题。

内容的提问来源于stack exchange,提问作者Chaim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:45:39