我的错误是:'search'被分配了一个值,但从未使用过。但我不知道它是否需要,如果需要,该放在哪里。
一切正常,搜索栏出现在我的表格上方,但似乎我的搜索栏没有链接到我的表格,我不能搜索任何东西。
import React, { useState, useEffect } from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import "bootstrap/dist/css/bootstrap.min.css";
import {Button, Badge} from "reactstrap";
export default function App() {
const [rowData, setRowData] = useState([]);
const [search, setSearch] = useState("");
const columns = [
{ headerName: "Title", field: "title" },
{ headerName: "Author", field: "author" },
{ headerName: "Edition Count", field: "editionCount" },
{ headerName: "Book ID", field: "id" }
];
useEffect(() => {
fetch("https://openlibrary.org/subjects/drama.json?published_in=2000")
.then(res => res.json())
.then(data => data.works)
.then(works =>
works.map(book => {
return {
title: book.title,
author: book.authors[0].name,
editionCount: book.edition_count,
id: book.cover_id
};
})
)
.then(books => setRowData(books));
}, []);
return (
<div className="container">
<h1>Book Catalogue</h1>
<SearchBar onSubmit={setSearch} />
<p>
<Badge colour="success">{rowData.length}</Badge> Books published in 2000
in the Drama category
</p>
<div
className="ag-theme-balham"
style={{
height: "300px",
width: "800px"
}}
>
<AgGridReact
columnDefs={columns}
rowData={rowData}
pagination={true}
paginationPageSize={7}
/>
</div>
<Button
colour="info"
size="sm"
className="mt-3"
href="https://openlibrary.org/developers/api"
target="_blank"
>
Go to Open Library API
</Button>
</div>
)
};
function SearchBar(props) {
const [innerSearch, setInnerSearch] = useState("");
return (
<div>
<input
aria-labelledby="search-button"
name="search"
id="search"
type="search"
value={innerSearch}
onChange={e => setInnerSearch(e.target.value)}
/>
<button
id="search-button"
type="button"
onClick={() => props.onSubmit(innerSearch)}
>
Search
</button>
</div>
);
}
有任何模板或教程,可以用来完成这个吗?到目前为止,我已经检查了几个并且更改了我的代码至少六次,但结果是一样的,所以我知道我做错了什么。
我不能评论,但你想做什么?如果你试图过滤你已经获取的数据,你应该使用filter方法:
useEffect(() => {
fetch("https://openlibrary.org/subjects/drama.json?published_in=2000")
.then(res => res.json())
.then(data => data.works)
.then(data => data.filter(book => book.title.includes(search))
.then(...)
或者你可以根据搜索的状态直接获取数据,为此,你需要指定查询,这取决于api的设置,但我会给你一个例子:
useEffect(() => {
fetch(`https://openlibrary.org/subjects/drama.jon?published_in=2000&name=${search}`)
.then(res => res.json())