Я работаю над созданием рабочего процесса динамических результатов поиска. Я могу сделать результаты без проблем, но не могу понять, как лучше их отключить, когда я удаляю все входные данные из панели поиска. Если вы начнете печатать, появятся адреса, которые совпадают, но затем, когда вы удалите все, они не исчезнут.
Я думал об использовании одного из двух параметров в моих переменных состояния: showMatches
или matches.length
. Я изо всех сил пытаюсь увидеть последний кусок этой головоломки. Ниже мой текущий код:
App.js
import React, { Component } from 'react';
import { Form, Button, ListGroup } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import Match from './Match';
//import Render from './Render';
const my_data = require('./data/test.json')
class App extends Component {
state = {
links: [],
selectedLink:null,
userLocation: {},
searchInput: "",
showMatches: false,
matches: [],
searchLink:[]
}
componentDidMount() {
fetch('https://data.cityofnewyork.us/resource/s4kf-3yrf.json')
.then(res=> res.json())
.then(res=>
//console.log(json)
this.setState({links:res})
);
}
handleInputChange = (event) => {
console.log(event.target.value)
event.preventDefault()
this.setState({searchInput: event.target.value })
this.updateMatches()
console.log(this.state.showMatches)
console.log(this.state.matches.length)
}
handleSubmit = (event) => {
event.preventDefault()
this.displayMatches();
}
findMatches = (wordToMatch, my_obj) => {
return my_obj.filter(place => {
// here we need to figure out the matches
const regex = new RegExp(wordToMatch, 'gi');
//console.log(place.street_address.match(regex))
return place.street_address.match(regex)
});
}
updateMatches =() => {
const matchArray = this.findMatches(this.state.searchInput, this.state.links);
const newStateMatches = matchArray.map(place => {
//console.log(place.street_address);
return place
});
this.setState({matches:newStateMatches})
this.state.matches.length > 1 ? this.setState({showMatches: true}) : this.setState({showMatches: false})
}
alertClicked = address => {
//event.preventDefault(); // not sure what event you're preventing
this.setState({searchLink: address});
this.pushData();
}
render() {
return (
<div>
<input
placeholder="Search for a Link Near you..."
onChange = {this.handleInputChange}
value = {this.state.searchInput}
/>
<ListGroup defaultActiveKey="#link1">
{
this.state.matches.map(match => {
return <Match
address={match.street_address}
alertClicked={this.alertClicked}
value = {this.state.searchLink}
logState={this.logState}/>
})
}
</ListGroup>
</div>
);
}
}
export default App;
Match.js
import React from 'react';
import { ListGroup } from 'react-bootstrap';
const match = ({ alertClicked, address }) => {
return (
<ListGroup.Item
className="Matches"
action
// function expressions could cause this to rerender unnecessarily.
onClick={(address) => alertClicked(address)}>
<p>{`${address}`}</p>
</ListGroup.Item>
)
}
export default match;
Оценитепомощь.