这是我们大学的作业。我尝试添加 useEffect 来改进我的小玩具项目以拥有 searchFilter 但它说
<块引用>类型错误:无法读取未定义的属性“过滤器”
关于 useEffect/setSearchFilter 部分
这是这个问题之前的情况。 我为这个问题持有这个超过 2 天感到灾难
/[错误图片][1]
谁能帮我解决这个问题?
import React, { useState, useEffect } from 'react'
import './App.css';
function App() {
const [datas, setDatas] = useState([]);
const [userid, setUserid] = useState('');
const [searchFilter, setSearchFilter] = useState('');
const inputChanged = (event) => {
setUserid(event.target.value)
}
useEffect(() => {
fetch('https://api.github.com/search/repositories?q=react')
.then(response => response.json())
.then(data => {
setDatas(data.items)
})
},[])
useEffect(() => {
setSearchFilter(
datas.full_name.filter((result) =>
result.name.toLowerCase().includes(userid.toLowerCase())
)
);
}, [userid, searchFilter]);
return (
<div className="App">
<h1>Repositories</h1>
<input
id="searchInput"
type="text"
placeholder="search"
name="search"
value={userid}
onChange={inputChanged}
/>
<button onClick={(e) => setSearchFilter(e.target.value)}>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
target="_blank"
href={data.html_url}
>
{data.html_url}
</a>
</td></tr>
)}
</tbody>
</table>
</div>
);
}
export default App;```
https://stackoverflow.com/questions/67761971/searchfilter-with-using-react-hookuseeffect-usestate/67762090#67762090
[1]: https://i.stack.imgur.com/RuubM.png
答案 0 :(得分:0)
如果您想过滤 useEffect
,这应该可以代替您的第二个 full_name
钩子。
useEffect(() => {
setSearchFilter(
datas.filter((result) =>
result.full_name.toLowerCase().includes(userid.toLowerCase())
)
);
}, [userid, searchFilter]);
答案 1 :(得分:0)
filter()
函数。代码如下:
import React, { useState, useEffect } from 'react'
import './App.css';
function App() {
const [data, setData] = useState([]);
const [userID, setUserID] = useState('');
const [searchResults, setSearchResults] = useState([]);
//Fetch data when mounted
useEffect(() => {
fetch('https://api.github.com/search/repositories?q=react')
.then(response => response.json())
.then(data => {
setData(data.items)
})
},[])
useEffect(() => {
let result = data.filter((d) =>
d.full_name.toLowerCase().includes(userID.toLowerCase())
)
setSearchResults(result);
}, [userID, data]);
const inputChanged = (event) => {
setUserID(event.target.value)
}
return (
<div className="App">
<h1>Repositories</h1>
<input
id="searchInput"
type="text"
placeholder="search"
name="search"
value={userID}
onChange={inputChanged}
/>
{/* No need for search button if searching using input (useEffect will trigger when typed)
<button onClick={search}>Search</button> */}
<table>
<tbody>
<tr>
<th>Name</th>
<th>URL</th>
</tr>
{searchResults.map((data, index) =>
<tr key={index}>
<td>{data.full_name}</td>
<td><a
target="_blank"
href={data.html_url}
>
{data.html_url}
</a>
</td></tr>
)}
</tbody>
</table>
</div>
);
}
export default App;
理想情况下,您希望同时处理加载状态和错误状态。