我正在搜索如何基于获取API结果的搜索栏。 API json结果返回了几个沙发,它们的名称和图像以及在这种情况下无关紧要的其他方面。我希望搜索基于沙发的名称,但是如果组件不是父母和孩子,我不知道该怎么做。我将在下面描述我的目录路径:
- src
-- components
--- Home
---- Main (Fetch request for name and image of sofas)
-- containers
--- other_files
--- Search
---- SearchBar.js (Here I need to make a filter search for the sofa name)
-- index.js
-- route.js
以下是获取结果json:
[
0:
brand:
created_on: "2017-05-02T10:27:23.905454Z"
id: 1
image: "/media/filer_public/ac/0b/ac0ba5cb-4f00-4386-aa8b-984919abdf8d/logoluso.png"
name: "LUSOGRAPH"
updated_on: "2018-04-09T08:22:52.022891Z"
category: null
code: "8ed96b9c"
created_on: "2017-05-02T10:28:11.951052Z"
description: "<p><strong>PELE</strong></p>"
fabric_color_number: 1
id: 1
image: "/media/filer_public/f3/59/f3596b6f-1d15-46a5-9b40-f2c275bfd65c/ancora.png"
is_active: true
name: "ÂNCORA"
updated_on: "2018-06-18T09:31:07.512569Z"
1:
{id: 2, brand: {…}, category: null, is_active: true, code: "534e44bc", …}
]
此外,我还将把 SearchBar.js 文件中的searchBar的代码放在此处:
import React from 'react';
export class SearchBar extends React.Component {
render() {
return (
<div id="SearchBar">
<form>
<input type="text" placeholder="Pesquisa" />
</form>
</div>
)
}
}
现在是 Main.js 页面的代码:
import React from 'react';
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
models: []
};
}
componentDidMount() {
/* Fetch's to get token */
fetch(url + '/couch-model/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results
}, () => {});
})
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return (<div>Loading...</div>)
} else {
return (
<div>
{models.map(model =>
<a href="/sofa" key={model.id}>
<div className="Parcelas">
<img src={"url" + model.image} className="ParcImage" alt="sofa" />
<h1>Sofá {model.name}</h1>
<button className="Botao">
<p className="MostraDepois">Ver Detalhes</p>
<span>+</span>
</button>
<img src="../../img/points.svg" className="Decoration" alt="points" />
</div>
</a>
)}
</div>
)
}
}
}
我不想用结果创建新页面,我希望结果与您在 Main.js返回代码中看到的内容相同,这意味着我只想我想限制获取的结果...
感谢您的任何帮助(如果没有Redux,可能的话),谢谢!
答案 0 :(得分:0)
我会将搜索文本放置在redux中。 您主要需要查看redux搜索文本。
在这一点上,您必须使用以下内容:
const filteredSofas = search === '' ? sofas : filter(sofa => sofa.name.toLowerCase().includes(search.toLowerCase()), sofas);
您的主体应着眼于redux搜索,这将是这样的:
const mapStateToProps = (state) => ({search: state.search});
export default compose(connect(null, mapDispatchToProps))(Main)