【问题标题】:(React-Select hooks) How can I update state using Select's onChange render prop?(React-Select 挂钩)如何使用 Select 的 onChange 渲染道具更新状态?
【发布时间】:2021-04-08 09:07:43
【问题描述】:

我尝试了很多方法,但我无法让 onChange 工作。我正在开发一个搜索栏组件,该组件在用户未更改搜索栏输入 3 秒后进行 fetch 调用,但我在更改 userSearchInput 状态挂钩时遇到问题,该挂钩会在 useEffect 中触发 api 调用。这是代码的最小化版本:

    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("test");
      }
    }, 3000);
    return () => clearTimeout(timer);
  }, [userSearchInput]);

  const handleSearchInputChange = (event) => {
    setUserSearchInput(event.target.value);
    console.log("input changed");
  };

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

关于我哪里出错了有什么想法吗?

【问题讨论】:

    标签: javascript reactjs react-hooks react-select


    【解决方案1】:

    选择包含“标签”和“值”的对象的值

    另外,react select 已经在函数的参数中返回值,所以你所要做的就是使用它

    const handleSearchInputChange = (selectedOptionObj) => {
        setUserSearchInput(selectedOptionObj);
        console.log("input changed");
      };
    

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 2021-11-11
      • 2018-05-20
      • 2022-01-17
      • 2021-03-22
      • 2022-01-24
      • 1970-01-01
      • 2020-03-12
      • 2019-08-16
      相关资源
      最近更新 更多