【问题标题】:searchfilter with using react hook(useEffect / useState)使用反应钩子的搜索过滤器(useEffect / useState)
【发布时间】:2021-08-18 01:34:20
【问题描述】:

我正在尝试创建一个搜索栏。 当我在输入中键入一些值时,我希望将来自 github api 的列表项与 searchBar 上的值一起重新列出。

import './App.css';

function App() {

  const [datas, setDatas] = useState([]);
  const [userid, setUserid] = useState('');
  
  const inputChanged = (event) => {
    setUserid(event.target.value)
  }

  const searchBar = () => {

  }

  useEffect(() => {

    fetch('https://api.github.com/search/repositories?q=react')
    .then(response => response.json())
    .then(data => {
      setDatas(data.items)
    })
  },[])
  return (
    <div className="App">
      <h1>Repositories</h1>
        <input id="searchInput"type="text" placeholder="search" name="search" value={userid} onChange={inputChanged}/>
        <button onClick={searchBar}>Search</button>
      <table>
        <tbody>
          <tr>
           <th>Name</th>
           <th>URL</th>
          </tr>
          {
          datas.map((data, index) => 
           <tr key={index}>
             <td>{data.full_name}</td>
             <td><a href={data.html_url}>{data.html_url}</a></td>
           </tr>
          )
        
          }
        </tbody>
      </table>
    </div>
  );
}

export default App; 

这是我的代码和本地主机的图像

【问题讨论】:

  • 阅读this answer 了解如何使用查询参数,然后使用上述方法更改您的搜索,而不是硬编码?q=react

标签: reactjs react-native react-hooks searchfiltercollection


【解决方案1】:

useEffect 末尾有一个数组,当留空时,useEffect 中的内容仅更新一次。您可以将变量添加到该数组中,以便在该变量更改时进行更新。

这里需要写:useEffect(your function,[userid]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多