我正在创建一个搜索栏。用户编写请求,然后按相应的过滤器按钮,该请求将存储在search
中,并通过Axios发送,最后返回结果。但是,我在控制台中得到了很好的结果(后面没问题),但只有在尝试使用版本过滤器(使用标题过滤器就可以)时,我才设法在页面中显示数据。我有此错误:未处理的拒绝(TypeError):无法读取未定义的属性“ livres”。我可以在代码中进行哪些广告/更改?
import React, {Component} from 'react';
import {
MDBContainer,MDBCol, MDBBtn,
} from 'mdbreact';
import "./accueil.css";
import axios from 'axios';
import { MDBDropdown,
MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem, } from "mdbreact";
class HomePage extends Component{
constructor(props){
super(props);
this.state = {
search:'',//va contenir la valeur entrée dans la barre de recherche
filter: [],//va contenir les resultats de la recherche
error:'',//va contenir l'erreur en cas d'erreur
}
this.searchTitle = this.searchTitle.bind(this);
this.searchEdition = this.searchEdition.bind(this);
}
change = e => {
this.setState({
[e.target.id]: e.target.value,
});
}
//search with the title filter
searchTitle = (search) => e => {
console.log(search);
let formData = new FormData();
formData.append("title",search);
const url = "http://localhost:8888/API/Accueil/recherche_titre.php"
axios.post(url, formData)
.then(response => response.data)
.then((data) => {
this.setState({filter: data.results.livres});
console.log(this.state.filter)
})
setTimeout(() => {
this.setState({
error: '',
});
}, 2000);
e.preventDefault();
}
//search with the edition filter
searchEdition = (search) => e => {
console.log(search);
let formData = new FormData();
formData.append("edition",search);
const url = "http://localhost:8888/API/Accueil/recherche_edition.php"
axios.post(url, formData)
.then((data) => {
this.setState({filter: data.results.livres});
console.log(this.state.filter)
})
setTimeout(() => {
this.setState({
error: '',
});
}, 2000);
e.preventDefault();
}
render() {
return(
<div>
<div className="searchPosition">
<MDBCol>
<div className="active-pink-3 active-pink-4 mb-4">
<input className="form-control" type="text" placeholder="Search..." aria-label="Search" />
</div>
</MDBCol>
</div>
<br></br>
<div >
<ul className="ulFilter">
<li className="liFilter">Choose a filter </li>
<li className="liFilter">
<MDBBtn onClick={this.searchTitle(this.state.search)} color="dark" size="lg">Titre</MDBBtn>
</li>
<li className="liFilter">
<MDBBtn onClick={this.searchEdition(this.state.search)} color="dark" size="lg">Edition</MDBBtn>
</li>
</ul>
<ul className="resultsSearch">
{ this.state.filter ? this.state.filter.map(book => (
<li className=".liResults" key={book.id}>{book.title},{book.edition}</li>
)) : <em>Loading</em>}
</ul>
</div>
</div>
);
}
}
export default HomePage;
答案 0 :(得分:0)
在searchEdition
中处理响应时,您似乎缺少此步骤:
.then(response => response.data)