【发布时间】:2021-09-24 14:46:45
【问题描述】:
我一直在谷歌搜索试图解决我的问题,但没有成功。
首先我明白“.map”是一个数组的方法,但变量“restaurants”在我的useState中。所以我不明白为什么我会收到错误“TypeError:restaurants.map is not a function”。
我正在尝试在我一直在研究的 PRN 应用中实现搜索功能。这是我的搜索组件。
请帮助我了解可能出了什么问题。这是完整的repo,以防这段代码不够用。
搜索组件:
import React, { useState } from "react";
function Search() {
const [name, setName] = useState("");
const [restaurants, setRestaurants] = useState([]);
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const response = await fetch(
`http://localhost:3001/api/v1/restaurants/?name=${name}`
);
const parseResponse = await response.json();
setRestaurants(parseResponse);
} catch (err) {
console.error(err.message);
}
};
return (
<>
<div className="mb-4">
<form className="form-row" onSubmit={onSubmitForm}>
<input
type="text"
name="name"
placeholder="Search"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
<table className="table my-5">
<thead>
<tr>
<th>Restaurant</th>
</tr>
</thead>
<tbody>
{restaurants.map((restaurants) => (
<tr key={restaurants.restaurants_id}>
<td>{restaurants.name}</td>
<td>{restaurants.location}</td>
</tr>
))}
</tbody>
</table>
{restaurants.length === 0 && <p>No Results Found</p>}
</div>
</>
);
}
export default Search;
server.js 中的文件:
app.get("/api/v1/restaurants", async (req, res) => {
try {
const { name } = req.query;
const restaurants = await pool.query(
"SELECT * FROM restaurants WHERE name || ' ' ||",
[`%${name}%`]
);
res.json(restaurants.rows);
} catch (err) {
console.error(err.message);
}
});
【问题讨论】:
-
parseResponse的内容是什么? -
应该是我的 Postgres 数据库中的内容。从 api 获取的名称。
-
我认为你必须处理你的空餐厅数组,直到它的状态从 HTTP 响应中得到更新。您可以尝试在您的反应代码中更改它吗 -
<tbody> { restaurants.length > 0 && restaurants.map((restaurants) => (...) } <tbody> -
酷。有了这个,我得到了 .map 不是一个函数,但是 SQL 没有返回带有搜索的过滤器。
{restaurants.length > 0 && restaurants.map((restaurants) => ( <tr key={restaurants.restaurants_id}> <td>{restaurants.name}</td> <td>{restaurants.location}</td> </tr> ))} -
你能做你的
select * from ...查询的console.log()并尝试在postgre SQL接口上运行那个普通的查询吗?或将其粘贴到此处,以便我们找出语法错误(如果有)。
标签: javascript sql reactjs postgresql