gpt4 book ai didi

reactjs - 为什么随机用户 api 的搜索功能不起作用?

转载 作者:行者123 更新时间:2023-12-04 08:28:50 26 4
gpt4 key购买 nike

我正在处理随机用户 api,获取用户名和分页工作正常,但不是搜索事件。请帮忙。
我把我的代码推到了 stackblitz 上,以帮助你们轻松调试它。
这是链接:https://stackblitz.com/edit/search-and-pagination-in-react-by-react-hooks?file=src/App.js
在下面的图片中,您可以看到我在搜索框中提到的名称出现在 api 中,但它没有出现在第一位。
enter image description here

最佳答案

Working example in here .

const App = () => {
const [myApi, setMyApi] = useState([]);
const [data, setData] = useState([]); // add your data to here
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const [searchUser, setSearchUser] = useState("");

useEffect(() => {
fetch("https://randomuser.me/api/?results=50")
.then(data => data.json())
.then(json_result => {
setData(json_result.results); // set your data to state
let myApi = renderData(json_result.results); // render your component
setMyApi(myApi); // set it to state
});
}, []);

const renderData = (data) => {
return data.map((item, idx) => {
return (
<div key={idx}>
<img src={item.picture.thumbnail} alt="" /> {item.name.first}
<hr />
</div>
);
});
}

// get current post
const indexOfLastPost = currentPage * postsPerPage; // 1 * 10 = 10
const indexOfFirstPost = indexOfLastPost - postsPerPage; // 10 - 10 = 0
const currentPosts = myApi?.slice(indexOfFirstPost, indexOfLastPost); // 0 to 10

// search users by user input
const handleSearchInput = event => {
setSearchUser(event.target.value);
const newData = renderData(data.filter(item => item.name.first.toLowerCase().includes(event.target.value))); // render filtered data
setMyApi(newData); // and set it to state
};

const paginate = pageNumber => setCurrentPage(pageNumber);

return (
<div>
<Search onChange={handleSearchInput} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={myApi?.length}
paginate={paginate}
/>
{currentPosts}
</div>
);
};

const Search = ({ onChange }) => {
return (
<div>
<input
type="text"
autoFocus={true}
placeholder="search users"
onChange={onChange}
/>
</div>
);
};

关于reactjs - 为什么随机用户 api 的搜索功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65127589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com