使用反应钩子搜索过滤器(useEffect/useState) [英] searchfilter with using react hook(useEffect / useState)

查看:38
本文介绍了使用反应钩子搜索过滤器(useEffect/useState)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

import './App.css';功能应用(){const [datas, setDatas] = useState([]);const [userid, setUserid] = useState('');const inputChanged = (事件) =>{setUserid(event.target.value)}const searchBar = () =>{}useEffect(() => {fetch('https://api.github.com/search/repositories?q=react').then(response => response.json()).then(数据=> {setDatas(data.items)})},[])返回 (

<h1>存储库</h1><input id="searchInput"type="text";占位符=搜索"名称=搜索"value={userid} onChange={inputChanged}/><button onClick={searchBar}>搜索</button><表格><tr><th>姓名</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>

);}导出默认应用程序;

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

解决方案

useEffect 在末尾有一个数组,当为空时 useEffect 中的内容只更新一次.您可以向该数组添加变量,以便在该变量更改时进行更新.

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

I am trying to create a searchBar. When I type some value on input, I would like my listitems from github api to be re-listed with the value on 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; 

Here is my code and the image of the localhost

解决方案

useEffect has an array at the end, when left empty what's in useEffect only update once. You can add variables to that array, to update when that variable changes.

Here you need to write: useEffect(your function,[userid]);

这篇关于使用反应钩子搜索过滤器(useEffect/useState)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆