javascript - 我在 react 中的过滤器搜索列表不显示过滤后的列表并遇到错误
问题描述
这是 Owner 组件(Owner.js),我在其中实现了一个搜索过滤器,它应该显示与搜索名称相同的餐厅。但是当我尝试使用餐厅并实施过滤器搜索时,它会出错。我应该从所有者仪表板中的现有餐厅列表中获取餐厅列表。
import React, { Component } from "react";
import Restaurant from "../customer/Restaurant";
export default class Owner extends Component {
constructor() {
super();
this.state = {
search: ""
};
}
updateSearch(event) {
this.setState({
search: event.target.value.substr(0, 25)
});
}
render() {
let filteredRestaurants = this.props.restaurants;
return (
<div>
<h1> Welcome Owner </h1> <br />
<ul>
{" "}
{filteredRestaurants.map(res => {
return <restaurants res={<Restaurant />} key={res.name} />;
})}
</ul>{" "}
<input
type="text"
Value={this.state.search}
onChange={this.updateSearch.bind(this)}
/>{" "}
<Restaurant />
</div>
);
}
}
这是 Restaurant.js,它在 Owner.js 中显示餐厅的详细信息。
import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getRestaurant } from "../../actions/getRestaurants";
export class Restaurant extends Component {
static propTypes = {
// restaurants: PropTypes.array.isRequired,
getRestaurantName: PropTypes.func
};
componentDidMount() {
this.props.getRestaurant();
}
render() {
const contentKeys = Object.keys(this.props.restaurants);
// console.log(JSON.parse(this.props.restaurants))
return (
<div className="row">
{contentKeys.map(t =>
[this.props.restaurants[t]].map(res => (
<div className="col-md">
<div className="card" style={cardWidth}>
<img className="card-img-top" src="..." alt="Card image cap" />
<div className="card-body">
<h5 className="card-title">{res.Name}</h5>
<p className="card-text">
<h6>{res.Address}</h6>
<h6>{res.City}</h6>
<h6>{res.zipcode}</h6>
<h6>Open:{res.Hours.Open}</h6>
<h6>Close:{res.Hours.Close}</h6>
</p>
<a href="#" className="btn btn-primary">
Go somewhere
</a>
</div>
</div>
</div>
))
)}
</div>
);
}
}
const cardWidth = {
width: "18rem"
};
const mapStateToProps = state => ({
restaurants: state.restaurantReducer.restaurants
});
export default connect(
mapStateToProps,
{ getRestaurant }
)(Restaurant);
//export default Restaurant;
我从所有者仪表板过滤餐厅时出错。由于 return 语句不返回任何值并遇到错误。
{filteredRestaurants.map(res => {
return <restaurants res={<Restaurant />} key={res.name} />;
})}
解决方案
您将搜索查询存储在一个状态中,但在呈现过滤餐厅时不要使用它。
您应该在映射之前过滤它们。像这样的东西:
const filteredRestaurants = this.props.restaurants.filter(res => res.name.includes(this.state.search);
// ...
filteredRestaurants.map(res => <Restaurant key={res.name} />)
此外,如果您使用的是 16.8+ React,则可以使用React Hooks API使其变得更容易。
推荐阅读
- c# - 使用 C# 和 microsoft PDF 打印机打印多页
- django - 如何仅使用 heroku 上的 postgres 转储来恢复我的数据库数据
- python - Python 嵌套类中的 super()
- agora.io - 如何使用 Agora 的 Web SDK v4.x 将本地麦克风静音并触发静音事件
- reactjs - 如何解决这种意外使用逗号运算符?
- r - 获得学生化残差
- sql - 如何使用 SQL 在 excel 中运行查询?引用 jdoodle 上的表格?
- micropython - micropython 简单的 pin 输入不起作用(树莓派 pico)
- mysql - Mysql查询以查找包含“非罗马”字母的任何条目
- asp-classic - 如何使用经典 ASP 使用 Swish QR Code API?