简体   繁体   English

(React-Select 挂钩)state 在 React-Select onChange 道具处理时不改变

[英](React-Select hooks) state not changing when React-Select onChange prop handling

I've tried quite a few methods but I have not been able to get onChange to update the userSearchSuggestion state.我已经尝试了很多方法,但我无法通过 onChange 更新 userSearchSuggestion state。 I'm working on a search-bar component that makes a fetch call after the user has not changed the search bar input for 3 seconds, but it appears that onChange is not firing at all when text is added to the component.我正在开发一个搜索栏组件,该组件在用户未更改搜索栏输入 3 秒后进行 fetch 调用,但似乎在将文本添加到组件时 onChange 根本没有触发。 Here is the code:这是代码:

    import React, { useState, useEffect } from "react";
import Select from "react-select";

export default function SearchBar() {
  const [userSearchInput, setUserSearchInput] = useState("");
  const [searchSuggestions, setSearchSuggestions] = useState([]);


  useEffect(() => {
    const searchSuggestions = async (searchInput) => {
      console.log("api called");
      const searchSuggestions = await fetch(
        "API STUFF"
      )
        .then((response) => response.json())
        .then((data) => {
          setSearchSuggestions(data.quotes);
        });
    };

    const timer = setTimeout(() => {
      if (userSearchInput !== "") {
        searchSuggestions(userSearchInput);
      }
    }, 3000);
    return () => clearTimeout(timer);
  }, [userSearchInput]);

  return (
    <Select
      value={userSearchInput}
      options={searchSuggestions}
      onChange={(e) => setUserSearchInput(e.currentTarget.value)}
      placeholder="Search a ticker"
    />
  );
}

Any ideas on why onChange is not updating the state?关于为什么 onChange 不更新 state 的任何想法? Even if I simply console.log(e) on onChange, nothing is logged into the console.即使我只是在 onChange 上使用 console.log(e),也没有任何内容记录到控制台中。

If you want to call the API when the user types in the Select input, use onInputChange instead of onChange .如果您想在用户输入Select输入时调用 API,请使用onInputChange而不是onChange

  • Use onChange when you want to execute some code when the user selects something.当您想在用户选择某些内容时执行某些代码时,请使用onChange
  • Use onInputChange when you want to execute some code when the user types something.当您想在用户键入某些内容时执行某些代码时,请使用onInputChange
<Select onInputChange={(input) => console.log(input)}

I also see you want to delay the API calls a bit when the user is typing.我还看到您想在用户键入时稍微延迟 API 调用。 It's a good practice, but the conventional way to do that is to use debounce or throttle .这是一个很好的做法,但传统的做法是使用debouncethrottle You can see the different between them here .你可以在这里看到它们之间的不同。

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

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